在节点/表达中启用了CORS,但是获得“对预检请求的响应未通过访问控制检查". [英] Enabled CORS in node/express but getting "Response to preflight request doesn't pass access control check"

查看:145
本文介绍了在节点/表达中启用了CORS,但是获得“对预检请求的响应未通过访问控制检查".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了错误:

无法加载 http://localhost:3000/users/register :对预检请求的响应未通过访问控制检查:所请求的资源上不存在"Access-Control-Allow-Origin"标头.因此,不允许访问来源' http://localhost:8080 .

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.

在前端,我正在使用axios:

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

在服务器端使用express我正在使用cors:

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

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

我得到的响应码为200,我确实看到了"Access-Control-Allow-Origin"标头,但服务器端却什么也没有.有什么想法吗?

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?

推荐答案

您很可能还需要显式启用对OPTIONS请求的支持(即"CORS预检").参见 https://github.com/expressjs/cors#enabling-cors-pre -flight ,了解有关操作方法的详细信息.

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));

这篇关于在节点/表达中启用了CORS,但是获得“对预检请求的响应未通过访问控制检查".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆