AngularJs, difference between complete $http post and shorthand $http.post - angularjs

when I post Object data from app.js to homecontroller using two different methods (complete $http.post and shorthand $http.post) like below:
var book = {
"title" : $scope.addTitle,
"publisher" : $scope.publisherSelected[0],
"authors" : $scope.authorsSelected,
"genres" : $scope.genresSelected
};
//This one posts data successfully:
$http({
method : 'POST',
url : '../administrator/addBook',
data : book,
}).
//This one fails:
$http.post("../administrator/addBook", {
data : book
},
What is the difference between them? I thought they were the same.

When you use the shorthand post method, the second argument itself is the data, so no need to add a wrapper {data:book} there (Adding it must be breaking your contract with the server, you can inspect the data being sent using the network console of the browser). So the difference between both the apis is only the way you set the configuration.
So
$http({
url: 'someurl',
data: someData, //Post data 2nd argument in http.post
method: 'POST', //implicit in case of http.post
config: { //This goes in as third argument
headers: someheadersObj,
transformRequest : someTransformFunc,
...
}
});
will be
$http.post('someurl', book, {
headers: someheadersObj,
transformRequest : someTransformFunc,
...
})
i.e, you need to do just this:
$http.post("../administrator/addBook", book)
Documentation
post(url, data, [config]);
Read this for all the configuration available.

Related

angular POST not working with servlet

I am trying to use angularjs POST (or even GET) to a servlet with the following:
var json = { hello: "world" }
var deffered = $q.defer();
$http({
method: "POST",
url: url,
headers: { "Content-Type" : "application/json" },
request: JSON.stringify(json)
}).then(data) {
if(data.data) {
deferred.resolve({
response : data
});
)
})
return deffered.promise;
within the servlet, simple:
String val = request.getParameter("request")
it never seems to see it
I have tried:
data: JSON.stringify({ request: json })
data: { request: json }
"request" : JSON.stringify(json)
etc
if I comment out the getParameter and just return a generic value using Gson
JsonObject json = new JsonObject();
json.addProperty("This", "works");
response.getWriter().print(new Gson().toJson(json));
that comes back fine so is there something within the angular POST I am doing wrong here? I have also tried using "GET" instead but same result.
EDIT: I would like to understand POST method and the "proper" way to get the data from the json object if getParameter is wrong please~
getParameter() returns http request parameters, you should add this params by using :
params: JSON.stringify(json)
Not with
request: JSON.stringify(json)
Take a look in params in get and params in post.

angular: pass additional data with form submit

At the moment i am using below code and it is working fine.
$scope.processForm = function($scope.formData) {
$http({
method : 'POST',
url : 'process.php',
data : $.param($scope.formData), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
Now i have one small requirement. I need to pass user id(uid) along with the form data.
In Jquery it is quite simple but I am new to angular and don't have much experience.
Any advise how i can pass the additional data in Angular.
Thanks
You can encapsulate your formData with your uid parameter togheter in an object expl :
var allData={'formData': $scope.formData, 'uid': $scope.uid}
And then pass in the allData Object to your post method data : allData.
If you encounter any problem getting data in you process.php (undefined data for example), you should let Angular pass data with content type application/json (default behavior of angularjs) and in your process.php you do like this :
$postContent= file_get_contents("php://input");
$req= json_decode($postContent);
$formData= $req->formData;
$uid= $req->uid;
Note that it will be great if you test with some static values first ( 'uid' : 2 ) to make sure that it works fine
you can send an object (associative array in php ) in $http data parameter:
$scope.processForm = function($scope.formData) {
console.log($scope.formData);
$http({
method : 'POST',
url : 'process.php',
data : {'data': $scope.formData,'userid':userid}, // no need to use $.param, even never see it in angular
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
see https://scotch.io/tutorials/submitting-ajax-forms-the-angularjs-way for details on how to get data in php side

Parameter in cloud function using Parse and Angular $resource

I am trying to call this [cloud function]..
Parse.Cloud.define("getMyData", function(request, response) {
console.log('request is : '+JSON.stringify(request));
console.log('parameter is : '+request.params.name);
//...
response.success('Run method successfully');
});
using Parse REST api from an Angular front end.
$resource 'https://api.parse.com/1/functions/getMyData', {},
myCustomMethod:
method: 'POST'
headers:
'X-Parse-Application-Id': 'FjV0J.....'
'X-Parse-REST-API-Key': 'Tr7Sipvu....'
params:
name: 'William'
My cloud function gets called, but I can't seem to retrieve my name parameter :
I2015-05-16T00:51:08.497Z]request is : {"body":"{}","params":{},"installationId":"","user":null,"master":false}
I2015-05-16T00:51:08.497Z]parameter is : undefined
Why doesn't my parameter appear in params?
Is there a problem with using Angular $resource to make such API calls?
What put me on the right path was that it worked great when using a curl call - as documented here.
In the end, I was able to retrieve my parameter by using $http instead of $resource :
// In controler
$http.post 'https://api.parse.com/1/functions/getMyData'
,
name: 'William'
,
method: 'POST'
headers:
'X-Parse-Application-Id': 'FjV0J.....'
'X-Parse-REST-API-Key': 'Tr7Sipvu....'
.success (data) ->
$scope.data = data
It appears Parse expects parameters to be transmitted through data which isn't possible with Angular $resource.

Slim, Postman and AngularJs : $app->request->getBody() vs $app->request->post()

I'm a beginner. I've written a test application made of an AngularJs GUI on the client side and a PHP API on the server side.
This is the angular service handling the requests
myApp.factory('Book', ['$resource', 'API_URL', function($resource, API_URL){
return $resource(API_URL + '/books/:bookId', {bookId: '#bookId'}, {
get: { method: 'GET', isArray:true },
update: { method: 'PUT'},
save: { method: 'POST'},
delete: {method:'DELETE'},
});
}]);
When I submit a book from the Angular app I can catch the POST in Slim by using
$post_a = json_decode($app->request->getBody());
//$post_b = $app->request->post(); //this would be empty
When I use Postman and I perform a POST I can catch the POST in Slim by using
//$post_a = json_decode($app->request->getBody()); // this would be empty
$post_b = $app->request->post();
I don't get why there is this difference. Could you please explain?
Am I not meant to catch the post just with $app->request->post(); in both the cases? Why the post coming from Angular can be caught only with $app->request->getBody()?
The $app->request->post() method retrieves key/value data submitted in a application/x-www-form-urlencoded request. If the request uses a different content-type (e.g. application/json), you can retrieve the raw request body with the $app->request->getBody() method and decode it as necessary. Let me know if you have further questions.
You could still use
$post_b = $app->request->post()
in Slim.
As long as you call this REST service from html form (AngularJS) by passing the data as form value formatted instead of as JSON.
If in AngularJS you have the data in JSON format, you have to translate it first into form. Below is the example how to invoke this REST service:
Object.toparams = function ObjecttoParams(obj) {
var p = [];
for (var key in obj) {
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
};
$http({
method: 'POST',
url: url,
data: Object.toparams(myobject),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
myobject is the data in JSON format that is going to be created
Thanks Josh..Your answers works for me.
Steps to follow:
1.You need to send request in json format under raw tab like this:
{"username":"admin","password":"admin"}
2.You need to set Content-Type to application/json in the headers.
That's it and it will work.

Extend angularjs $resource service to include common headers

I want to write a wrapper service to the existing angular $resource service such that some custom headers are added to the http request by default. I am aware that we can set common headers using $httpProvider.defaults.headers.common. But this way all my requests would have this header and that is not what I want.
It would be lot more cleaner if the $resource service could be extended into a wrapper service in which I can define these common headers. This way I could selectively use this wrapper service wherever the common headers need to be added.
This may not be the answer you're looking for but I will share my thoughts. I'm using angular $http. The way I do it is I specify the correct header in every api call.
Something like this:
authenticatePlayer: function(postData) {
return $http({
method : 'POST',
url : api + 'auth/player',
data : postData,
headers : {'Content-Type' : 'application/json'}
});
},
uploadAvatar: function(email_address, fd) {
return $http({
method : 'POST',
url : api + 'player/' + email_address + '/avatar',
data : fd,
withCredentials: true,
headers : {'Content-Type' : undefined, 'X-Token' : credential.token},
transformRequest: angular.identity //awesome! automatically set to the correct header request
});
},
fbLogin: function(data) {
var xsrf = $.param({fb_access_token: data});
// console.log(postData);
return $http({
method : 'POST',
url : api + '/user/v1/login',
data : xsrf,
headers : {'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'}
});
}
I'm not an expert in angular but this is the way I do it. Hope it helps :)

Resources