1

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?

bryan
  • 8,879
  • 18
  • 83
  • 166
  • According to [MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS): "Browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request method, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method. Servers can also notify clients whether "credentials" (including Cookies and HTTP Authentication data) should be sent with requests." [See this](http://stackoverflow.com/a/13030629/2852427) and the answers below. – Ekin Sep 04 '16 at 01:44

1 Answers1

2

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'
  }
})
PerfectPixel
  • 1,918
  • 1
  • 17
  • 18