简体   繁体   中英

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?

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'
  }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM