节点 JS CORS 模块未设置 Access-Control-Allow-Credentials 标头
Posted
技术标签:
【中文标题】节点 JS CORS 模块未设置 Access-Control-Allow-Credentials 标头【英文标题】:Node JS CORS module not setting Access-Control-Allow-Credentials header 【发布时间】:2017-03-21 00:09:32 【问题描述】:我正在尝试使用这样的 CORS 模块配置在 Node Js 中全局设置 Access-Control-Allow-Credentials 标头
`var cors = require('cors');
var corsOptions =
origin: true,
'Access-Control-Allow-Origin': 'localhost:1550'
'Access-Control-Allow-Credentials': 'true'
;
app.use(cors(corsOptions));`
这似乎不起作用,所以我也为尝试设置预检响应的路线设置了它。我是这样设置的
`router.options('/login', cors(corsOptions));`
我检查了 Chrome 开发者工具,发现 Access-Control-Allow-Origin
标头已设置,但未设置 Access-Control-Allow-Credentials
。我需要这个标头,因为我在 Angular 中设置了 withCredentials = true
。
为什么 Node JS 没有设置 Access-Control-Allow-Credentials 标头而设置了其他标头?
我知道这是因为我在控制台中收到以下错误
XMLHttpRequest cannot load http://www.localhost:1550/api/v1/auth/login. Response to preflight request doesn't pass access control check: Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials. Origin 'http://127.0.0.1:1550' is therefore not allowed access.
【问题讨论】:
【参考方案1】:您遗漏了有关您正在使用的库的详细信息。是快递吗?发布完整代码。
由于您只是明确指定标头,因此您可以删除 cors 模块。 你可以调整这个答案 In Node.js/Express, how do I automatically add this header to every "render" response?
【讨论】:
我正在使用 Express,就我为处理预检请求而编写的代码而言,该代码几乎就是它【参考方案2】:我认为您没有正确设置配置。如文档中所述
https://www.npmjs.com/package/cors#configuration-options
var corsOptions =
origin: 'localhost:1550',
credentials : true
这将设置凭据标头。 As Origin 设置 Access-Control-Allow-Origin 和 credentials 设置 Access-Control-Allow-Credentials。
【讨论】:
谢谢,我现在意识到我没有彻底扔掉文档以上是关于节点 JS CORS 模块未设置 Access-Control-Allow-Credentials 标头的主要内容,如果未能解决你的问题,请参考以下文章
AngularJS SpringSecurity CORS问题
尽管未设置 Access-Control-Allow-Credentials,但出现 CORS 错误
节点 JS - CORS 对预检请求的响应未通过访问控制检查:“Access-Control-Allow-Origin”标头的值