首页 文章

CORS:当credentials标志为true时,无法在Access-Control-Allow-Origin中使用通配符

提问于
浏览
204

我有一个涉及的设置

前端服务器(Node.js,domain:localhost:3000)<--->后端(Django,Ajax,域:localhost:8000)

浏览器< - webapp < - Node.js(服务应用)

浏览器(webapp) - > Ajax - > Django(服务ajax POST请求)

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

当credentials标志为true时,无法在Access-Control-Allow-Origin中使用通配符 .

在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 config:

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

4 回答

  • 177

    如果您使用 express ,您可以使用cors包来允许CORS,而不是编写您的中间件;

    var express = require('express')
    , cors = require('cors')
    , app = express();
    
    app.use(cors());
    
    app.get(function(req,res){ 
      res.send('hello');
    });
    
  • 11

    如果您使用的是CORS中间件并且想要发送 withCredential 布尔值,则可以像这样配置CORS:

    var cors = require('cors');    
    app.use(cors({credentials: true, origin: 'http://localhost:3000'}));
    
  • 11

    试试吧:

    const cors = require('cors')
    
    const corsOptions = {
        origin: 'http://localhost:4200',
        credentials: true,
    
    }
    app.use(cors(corsOptions));
    
  • 4

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

    除了 * 太过宽容并且会失败使用凭证 . 因此,将 http://localhost:3000http://localhost:8000 设置为允许原点标头 .

相关问题