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

当 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 我想在一个软件里添加一个优惠弹窗,应该怎么写代码
  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流