Enabled CORS in node/express but getting “Response to preflight request doesn't pass access control check”

*爱你&永不变心* 提交于 2020-01-25 06:08:10

问题


I am getting the error :

Failed to load http://localhost:3000/users/register: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

On the front end i'm using axios:

const instance = axios.create({
  baseURL: 'http://localhost:3000',
  timeout: 1000,
  headers: {"Access-Control-Allow-Origin": "*"}
});

instance.post('/users/register').then((res) => {
  console.log(res);
}).catch((err) => {
  console.log(err);
});

and on the server-side using express i am using cors:

var cors = require('cors');
var corsOptions = {
   origin: '*',
   optionsSuccessStatus: 200 
}
app.use(cors(corsOptions));

I am getting a response code of 200 and I do see the 'Access-Control-Allow-Origin' header but i'm not getting anything on the server-side. Any ideas?


回答1:


You most likely need to also explicitly enable support for OPTIONS requests (i.e. "CORS preflight"). See https://github.com/expressjs/cors#enabling-cors-pre-flight for details on how to do that.

For your specific case, I would add the following:

app.options('/users/register', cors(corsOptions));

Or if you want to enable it for all requests:

app.options('*', cors(corsOptions));


来源:https://stackoverflow.com/questions/50575762/enabled-cors-in-node-express-but-getting-response-to-preflight-request-doesnt

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