【问题标题】:Node JS CORS module not setting Access-Control-Allow-Credentials header节点 JS CORS 模块未设置 Access-Control-Allow-Credentials 标头
【发布时间】: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.

【问题讨论】:

    标签: angularjs node.js cors preflight


    【解决方案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。

    【讨论】:

    • 谢谢,我现在意识到我没有彻底扔掉文档
    猜你喜欢
    • 2015-04-14
    • 2022-10-13
    • 2013-01-22
    • 2016-03-15
    • 2019-01-18
    • 1970-01-01
    • 2018-09-19
    • 2022-01-13
    • 2019-06-19
    相关资源
    最近更新 更多