【发布时间】:2014-07-08 13:07:58
【问题描述】:
我有一个涉及
的设置前端服务器(Node.js,域:localhost:3000) 后端(Django,Ajax,域:localhost:8000)
浏览器
浏览器 (webapp) --> Ajax --> Django(服务 ajax POST 请求)
现在,我的问题在于 Web 应用程序用于对后端服务器进行 Ajax 调用的 CORS 设置。在 chrome 中,我不断得到
当凭证标志为真时,不能在 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/
)
【问题讨论】:
-
对我来说是没有http的localhost:3000,像这样:CORS_ORIGIN_WHITELIST = ('localhost:3000',)
-
你的意思是在一台PC上开发前端和后端?
-
不同PC的前端和后端怎么样?
-
@ixaxaar 为什么你说 http 对你有用?我们都只有 ''localhost:3000'' 有效。
-
@244boy 是的,重点不是
http,而是最后的/。我想省略 http 可能会起作用,但我已经有几年没有真正研究过这个东西了,所以现在真的不知道什么有效!
标签: ajax django node.js cors django-cors-headers