2

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.

6324
  • 4,678
  • 8
  • 34
  • 63
  • 1
    Tip: to investigate problems like that, hit F12 (Cmd-Alt-I on Mac) in the browser, click on the network tab, and compare the two requests. – JB Nizet Oct 26 '15 at 17:45
  • Possible duplicate of [AngularJs $http.post() does not send data](http://stackoverflow.com/questions/19254029/angularjs-http-post-does-not-send-data) – akashrajkn Oct 26 '15 at 19:42

1 Answers1

2

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.

PSL
  • 123,204
  • 21
  • 253
  • 243