0

Am I doing something wrong? When I do the following I receive no post variables in /url

$http.post("/url", { something: "something" })
    .success(function(data) {
        console.log(data);
    }).error(function(data){ alert("An error occurred. Please try again."); }
);
bryan
  • 8,879
  • 18
  • 83
  • 166
  • 2
    Take a look at this post: [AngularJs $http.post() does not send data](http://stackoverflow.com/questions/19254029/angularjs-http-post-does-not-send-data) – Fiete Jan 17 '16 at 22:19
  • Interesting. Thanks for this @Fiete - Learn something new everyday – bryan Jan 17 '16 at 22:29

2 Answers2

0

By default angular encodes data to Content-Type: application/json but you want it to be Content-Type: x-www-form-urlencoded. The later is set to default by jQuery post, thats why most of the newcomers fall into that trap.

So you have to set the content type before you do the request.

yourApp.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
}]);

Now before every http request, the content type is changed to what we set above.

Same topic is been discussed in this post.

Community
  • 1
  • 1
Subash
  • 7,098
  • 7
  • 44
  • 70
0

I had similar issues related to HTTP headers, the below works fine with me in all cases.

var data = {something: "something"};
$http({
    method: 'POST',
    url: url,
    data: data,
//Uncomment this if the problem persists, it's to explicitly state the content type.
    //headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
Muhammad Hani
  • 8,476
  • 5
  • 29
  • 44