我有一个设置
前端服务器(Node.js,域:localhost:3000) <——>后端(Django, Ajax,域:localhost:8000)
浏览器<——webapp <——Node.js(服务应用程序)
浏览器(webapp) -> Ajax -> Django(服务Ajax POST请求)
现在,我在这里的问题是CORS设置,web应用程序使用它来对后端服务器进行Ajax调用。在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中,我使用了这个中间件
web应用程序发出这样的请求:
$.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—禁用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/
)