bryan bryan - 3 months ago 11
AngularJS Question

Angularjs getting OPTIONS and POST request

I am sending a POST request to a different domain like so in angular:

$http.post('http://domain.com/auth', { email: $scope.email, password: $scope.password })


And in my request logs, it was only sending an OPTION request.

So I added this to my
domain.com/auth
:

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');


But now, I am getting an OPTION request first, and then a POST request. So because my OPTION request is first, I think it is still messing with my results.

Does anyone know how to only get the POST request and not the OPTIONS request?

Answer

You can prevent a preflight on POST by triggering a simple request

To achieve this, use $httpParamSerializerJQLike to encode your data (make sure to inject the serializer) and set the content-type to application/x-www-form-urlencoded:

$http({
  url: 'YOUR_ENDPOINT',
  method: 'POST',
  data: $httpParamSerializerJQLike(YOUR_DATA),
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})