derek5. 2013-11-02 15:18 采纳率: 100%
浏览 3859
已采纳

当 Cors 凭据标志为真时,不能在 Access-Control-Allow-Origin 中使用通配符!

我有个想法: 前端服务器(Node.js,domain: localhost: 3000)——后端(Django,Ajax,domain: localhost: 8000) 浏览器 -- webapp -- Node.js (为应用服务) Browser (webapp) -- Ajax -- Django (为 Ajax POST 请求服务) 现在问题是 CORS 设置,webapp 使用 CORS 设置对后端服务器进行 Ajax 调用。 在Chorme中,我不断得到:

Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true.

在火狐浏览器上也不行。

我的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中,我使用这个[中间件](https://gist.github.com/strogonoff/1369619 ""),同时使用webapp这样的请求:

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

因此,Web应用程序发送的请求头如下所示:

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

哪里出问题了?!

---

我尝试使用: chrome --disable-web-security, 但没有让其真正运作起来。

---

所以,我最终的解决方案是: 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/
)
  • 写回答

4条回答

  • 旧行李 2013-11-02 17:31
    关注

    This is a part of security, you cannot do that. If you want to allow credentials then your Access-Control-Allow-Origin must not use *. You will have to specify the exact protocol + domain + port. For reference see these questions :

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

    Besides * is too permissive and would defeat use of credentials. So set http://localhost:3000 or http://localhost:8000 as the allow origin header.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入