我有个安排

Frontend server (Node.js, domain: localhost:3000) <---> Backend (Django, Ajax, domain: localhost:8000)

浏览器&lt;——webapp&lt;—— node .js(为应用服务)

Browser (webapp) --> Ajax --> Django(Serve ajax POST requests)

现在,我的问题是CORS设置,webapp使用它来对后端服务器进行Ajax调用.在chrome中,我一直

当凭据标志为true时,无法在访问控制允许来源中使用通配符.

在firefox上也不起作用.

我的 node .js安装程序是:

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', 'http://localhost:8000/');
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
};

在Django我用的是this middleware along with this

webapp会发出如下请求:

$.ajax({
    type: "POST",
    url: 'http://localhost:8000/blah',
    data: {},
    xhrFields: {
        withCredentials: true
    },
    crossDomain: true,
    dataType: 'json',
    success: successHandler
});

因此,webapp发送的请求头如下所示:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: "Origin, X-Requested-With, Content-Type, Accept"
Access-Control-Allow-Methods: 'GET,PUT,POST,DELETE'
Content-Type: application/json 
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Cookie: csrftoken=***; sessionid="***"

以下是回复标题:

Access-Control-Allow-Headers: Content-Type,*
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE
Content-Type: application/json

我哪里出错了?!

编辑1:我一直在使用chrome --disable-web-security,但现在希望事情能真正起作用.

编辑2:答案:

所以,我的解决方案django-cors-headers配置:

CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
    'http://localhost:3000' # Here was the problem indeed and it has to be http://localhost:3000, not http://localhost:3000/
)

推荐答案

这是安全的一部分,你不能这么做.如果您想允许凭据,那么您的Access-Control-Allow-Origin不能使用*.您必须指定确切的协议+域+端口.参考请参见以下问题:

  1. Access-Control-Allow-Origin wildcard subdomains, ports and protocols
  2. Cross Origin Resource Sharing with Credentials

除此之外,*太过宽容,会阻碍凭证的使用.因此,将http://localhost:3000http://localhost:8000设置为allow origin标头.

Node.js相关问答推荐

在Cypress测试文件中获取项目根路径

如何在CustomGPT的 node 中使用服务器端事件(SSE)

node 无法验证第一个证书

使用OpenAI API时遇到问题

NodeJS中的Vertex AI GoogleAuthError

Mongodb - 在数组数组中查找()

如何在 require 方法中使用路径与node.js react ?

如何使用Next.js/Node/TS正确地上传至S3

如何在 node /快速服务器上配置 mongoDB

node_modules/preact/src/jsx.d.ts:2145:22 - 错误 TS2304:找不到名称SVGSetElement

结合后端(Express)和前端(Angular)路由

加速 sequelize ORM 中的查询

Mocha调用所有it回调模拟(测试中间件)

在 Express.js 中迭代子文档数组

使用 WebSockets 有服务器成本吗?

为什么我会收到错误:解决方法指定过多?

按日期时间字段获取最新的 MongoDB 记录

node.js 中存储的模块变量在什么范围内?

Selenium WebDriver 等到元素显示

我应该如何在 webpack 中使用时刻时区?