我正在尝试为我的django服务器实现cors支持。
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'userdetails.middleware.crossdomainxhr.XsSharing',
)
XS_SHARING_ALLOWED_CREDENTIALS = 'True'
XS_SHARING_ALLOWED_ORIGINS = '*'
XS_SHARING_ALLOWED_METHODS = ['POST','GET','OPTIONS', 'PUT', 'DELETE']
userdetails.middleware.crossdomainxhr.XsSharing'正是https://gist.github.com/strogonoff/1369619中的代码
当我在Chrome中使用ajax脚本调用此内容时,出现错误:
访问控制允许的源不允许源HTTP 'http://localhost:8002'
(我的本地Web服务器所在的位置)
知道我在这里做错了什么吗?
ajax脚本在这里:
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function () {
var url = 'http://xx.xxx.x.xxx/api/user/register/';
alert("going to make call, see the request/response in browser debuger/inspector");
$.ajax({
type: "POST",
contentType: "application/json",
dataType: "application/json",
url: url,
data: JSON.stringify({
'firstName': 'Corsnew',
'lastName': 'Corsnew',
'email': 'corsnewe@cors.com',
'password': 'cors',
}),
processData: false,
//contentType: "application/json; charset=utf-8",
// accept: 'text/plan',
origin: 'localhost',
complete: function (data) {
console.dir(data);
}
});
});
</script>
<title></title>
</head>
<body>
</body>
</html>
对chrome的回应是:
HTTP/1.1 200 OK
Date: Tue, 06 Aug 2013 07:33:09 GMT
Server: Apache/2.2.20 (Ubuntu)
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE
Access-Control-Allow-Headers: Content-Type,*
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 20
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=utf-8
答案 0 :(得分:2)
这两个标题是冲突的:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
不接受通配符,您需要指定要发送的凭据的来源。您的服务器只能回显传入请求的来源。
(https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)