Why do I get an OPTIONS request after making a POST request?

末鹿安然 提交于 2019-12-01 00:09:10

That OPTIONS request is sent automatically by your browser on its own, before it tries the POST request from your code. It’s called a CORS preflight.

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Preflighted_requests has the details.

The gist of it in your specific case is that the Content-Type: application/json request header that your code is adding is what triggers the browser to do that preflight OPTIONS request.

So the purpose of that particular preflight request is for the browser to ask the server, “Do you allow cross-origin POST requests that have a Content-Type header whose value isn’t one of application/x-www-form-urlencoded, multipart/form-data, or text/plain?”

And for the browser to consider the preflight successful, the server must send back a response with an Access-Control-Allow-Headers response header that includes Content-Type in its value.

So I see that you’ve got res.header('Access-Control-Allow-Headers', 'Content-Type') in your current server code on http://localhost:8000/, and that’s the right value to set if you’re going to code it manually that way. But I think the reason that’s not working is because you don’t also have code that explicitly handles OPTIONS requests.

To fix that, you might try instead installing the npm cors package:

npm install cors

…and then doing something like this:

var express = require('express')
  , cors = require('cors')
  , app = express();
const corsOptions = {
  origin: true,
  credentials: true
}
app.options('*', cors(corsOptions)); // preflight OPTIONS; put before other routes
app.listen(80, function(){
  console.log('CORS-enabled web server listening on port 80');
});

That’ll handle the OPTIONS request for you, while also sending back the right headers and values.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!