I want to make a POST request using Angular. I am using ng-submit to submit the form to the controller where I access the factory to make the request using:
$http.post('/droplets', data)
I need the data from the form fields to put in the "data" variable above to send to my API but I can't work out how to do this when it is more than one field. How is this done?
Try this...
$http({
url: '/droplets',
method: "POST",
data: JSON.stringify({application:app, from:data1, to:data2}),
headers: {'Content-Type': 'application/json'}
}).success(function (data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).error(function (data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
Ref:https://docs.angularjs.org/api/ng/service/$http
Related
In angular, I want to download a text file containing a csv of userdata. Usually I have a form with a post action, but I want the user to stay on the same page, but return the csv data without any page referesh. The following is my post command:
$http({
url: "api/getUserData",
method: "POST",
data:{user_id:app.user_id}
}).success(function(data, status, headers, config) {
// data gets returned here
}).error(function(data, status, headers, config) {
$scope.status = status;
});
My problem is, the "data" that comes back from the post is a csv file. how can I get the data to actually "download" to the user's computer instead of living in the javascript? Is this even possible?
Here is the link to solution. It uses HTML5 FileSaver API to save the file as BLOB
You can do this :
Create temporary anchor ,
encode, your data & name your file using download attribute,
and then, fire a click event on it.
finally, remove the inserted element .
$http({
url: "api/getUserData",
method: "POST",
data:{user_id:app.user_id}
}).success(function(data, status, headers, config) {
// data gets returned here
var anchor = angular.element('<a/>');
angular.element(document.body).append(anchor); // Attach to document
anchor.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURI(data),
target: '_blank',
download: 'myFileName.csv'
})[0].click(); // fire a click event.
anchor.remove(); // Clean it now ...
}).error(function(data, status, headers, config) {
$scope.status = status;
});
I've got a simple node.js backend build on Restify with OAuth2 authorization (restify-oauth2 plugin).
I've got a problem requesting a token. When I call POST method with my REST client, everything works correctly and I get access_token and token_type.
The problem occurs when I try to do the same thing in my frontend aplication made in Angular.
Here's my code:
var req = {
method: 'POST',
url: 'http://localhost:8080/token',
headers: headers,
data: {},
params: {grant_type: "client_credentials"}
};
$http(req).success(function(data, status, headers, config){
console.log('success');
}).error(function(data, status, headers, config){
console.log('error');
});
So as you can see, grant_type parameter is provided. But still the server responds with:
{"error":"invalid_request","error_description":"Must specify grant_type field."}
And here's devtools screenshot:
How do I need to change my request to make it work?
I finally solved it. The thing is that grant_type field must be passed inside a request body, not in the parameters.
Working request code:
var req = {
method: 'POST',
url: 'http://localhost:8080/token',
headers: headers,
data: "grant_type=client_credentials"
};
$http(req).success(function(data, status, headers, config){
console.log('success');
}).error(function(data, status, headers, config){
console.log('error');
});
$http({
url: Config.ApiURL + "/site/go",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param(testimony)
}).progress(function (data, status, headers, config) { //Not sure about this line
console.log('progressing');
}).success(function (data, status, headers, config) {
console.log('success');
});
I want to display something before it successes or error, so im not sure about .progress part, i just inserted it there as an example and for you to imagine my problem.. is it possible? is there a built-in function for that?
BTW, im new to angular. TIA :)
According to some post I found on github (https://github.com/angular/angular.js/issues/1934 , see the post from 26th april 2014), you should be able to do it like that :
$http({method: 'GET', url: '/someUrl',progress:trackProgress}).then(function(result){
// handle result
});
Where tarckProgress would be a callback to call to handle the progress state.
If you want to show the progress spinner / bar, and in addition to that if you want to show something else, you can use angular-loading-bar
Currently I'm working with paypal API and flowing with this document make your first call.
When I sent a request through angular $http to paypal, I got a Status Code 415. It's seems like I missed something, does anyone can help me? :)
here is my code
$http({
url: 'https://api.sandbox.paypal.com/v1/oauth2/token',
method: 'POST',
headers: {'Content-Type': 'application/json',
'auth-token': 'EOJ2S-Z6OoN_le_KS1d75wsZ6y0SFdVsY9183IvxFyZp EClusMEUk8e9ihI7ZdVLF5cZ6y0SFdVsY9183IvxFyZp',
'Accept-Language': 'en_US'
},
data: { 'grant_type': 'client_credentials' }
}).success(function (data, status, headers, config) {
console.log(data)
}).error(function (data, status, headers, config) {
console.log(data)
});
Referring to the Paypal doc
Tip: If you're using Windows, we recommend you make cURL calls using a
Bash shell. If you're not using cURL calls, set the content-type to
application/x-www-form-urlencoded for this request.
Try set the content_type as application/x-www-form-urlencoded
I am learning Angular.js. I tried to search many existing questions but could not find one matching question or answer.
I am sending a GET request to a java servlet and expecting an object from it. Here is the angular $http GET request
$http({
method:'GET',
url : '/JSONWebApp/json/?fqn=' + $scope.fqn
}).
success(function(data, status, header, config){
console.log('Success');
console.log("data - "+data);
console.log("status - " + status);
console.log("header - " + header);
console.log("config - " + config);
}).
error(function(data, status, header, config){
console.log('Error');
});
On java servlet, here is what I write in doGet method
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Incoming Request URI : " + request.getRequestURI());
**User user = new User();
request.setAttribute("user", user);
RequestDispatcher view = request.getRequestDispatcher("/html/index.html");
view.forward(request, response);**
}
When the response is returned from this servlet, it goes to success of $http service in angular side. From where I will get the user object which I sent from server.
When I add the console.log to print the data, it prints the /html/index.html contents which is where I am forwarding.
Based on my research, my angular code is correct but I am not setting things correctly in java servlet.(Does this help - How to access json return values in angular.js action success callback)
Thanks in advance.
Add the following line to the $http object:
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
Use POST method instead of GET
method: 'POST'
So in the end, we came up with something like this:
myData = {"name": "zezinho", "pass": "123xxx"};
$http({
method: 'POST',
url: 'Login',
data: myData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data) {
alert(data);
}).error(function () {
alert("login error");
});
You need to serialize your User object into a JSON string and put that in the response body. A library like Jackson can help but before you add that in and confusing yourself more just serialize it into a JSON string yourself. Don't forget to set the Content-Type header.