AngularJS can't send post request with Content-Type:application/json

Junv picture Junv · Jan 28, 2014 · Viewed 8.7k times · Source

Currently I am using angularJS and CoffeeScript to try to send a post request, and my sample code is:

login: (user, callback)=>
baseUrl = 'http://localhost:3000/api/v1/sessions'
@$http({
  method: 'POST',
  url: baseUrl,
  data: user
}).success (result)->
  callback(result)

But when I call it, it just send 'OPTIONS' request instead of POST request.
And the request detail is: enter image description here If I add header to this method,

login: (user, callback)=>
baseUrl = 'http://localhost:3000/api/v1/sessions'
@$http({
  method: 'POST',
  url: baseUrl,
  data: user,
  headers:
    'Content-Type': 'application/json'
}).success (result)->
  callback(result)

It still doesn't works, but if I change headers to 'Content-Type': 'application/x-www-form-urlencoded', then it can send post requests.
But the request Content-type is not not I want.

I also try to modify the request data to JSON by: data: JSON.stringify(user), but still not working.

UPDATES

Guys, I did another spike on this issue. Which is I am jquery to send the request and it works fine, but I found an wired thing that is they have different request data.

Jquery

$.ajax({
  type: "POST",
  url: "http://localhost:3000/api/v1/sessions",
  data: {
    "user":{
      "email":"[email protected]",
      "password":"123456"
    }
  },
  success: function(){

  }

Screenshot for Jquery enter image description here

Angular

login: (user, callback)=>
baseUrl = 'http://localhost:3000/api/v1/sessions'
@$http({
  method: 'POST',
  url: baseUrl,
  data: {
    "user":{
      "email":"[email protected]",
      "password":"123456"
    }
  },
  headers:
    'Content-Type': 'application/x-www-form-urlencoded'
}).success (result)->
  callback(result)

Now it can send request,but I just got 401 when trying to do request.
Screenshot for Angular enter image description here

So I think the issue may due to the format of the angular request data.

Answer

stride picture stride · Jan 28, 2014

You are hitting CORS restrictions and same origin policy.

Easiest solution is to deploy web frontend and the api together as one app. If ports are different even on the same machine then one needs to deal with same origin policy.

Options is a preflight query. Make your backend accept it and it should be fine.

More reading: http://www.html5rocks.com/en/tutorials/cors/