过去一小时我一直在阅读有关XMLHttpRequest的内容,但我似乎可以让这项工作成功。 所以,我有一个django服务器与tastypie和另一个服务器/端口上的JavaScript客户端,当我尝试做一个jquery帖子我得到一个
XMLHttpRequest cannot load http://127.0.0.1:8000/api/smart/rating/. Origin http://localhost is not allowed by Access-Control-Allow-Origin.
我在客户端
上收到Xmlthhprequest错误消息Django代码:
class RatingResource(ModelResource):
city = fields.ForeignKey(CityResource, 'city')
user = fields.ForeignKey(UserResource, 'user')
class Meta:
queryset = Rating.objects.all()
resource_name = 'rating'
#authentication = BasicAuthentication()
#authorization = DjangoAuthorization()
我的jquery呼叫从localhost发布:80到localhost:8000:
$('#star').raty({
path: "../assets/img/",
score : rating,
click : function(score, evt) {
window.rate_app = score;
var url = "http://127.0.0.1:8000/api/smart/rating/";
//var comment = $('#textarea').val();
var comment = "teste do php";
console.log(cityId);
$.post(url,{city : '/api/smart/city/'+cityId+'/' ,comment : comment,id:'4',resource_uri:'/api/smart/rating/4/',rating : score, user: '/api/smart/auth/user/2/'},function(data,status){
if (data=="error")
console.log("error");
else
console.log("success");
});
}
});
更新:
HTTP / 1.0 401 UNAUTHORIZED
curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"city": "/api/smart/city/35/", "comment": "teste do php", "id": "4", "resource_uri": "/api/smart/rating/4/", "rating": "3","user_id": "/api/smart/auth/user/2/"}' `http://localhost:8000/api/smart/rating/`
HTTP/1.0 401 UNAUTHORIZED
Date: Mon, 08 Apr 2013 10:52:44 GMT
Server: WSGIServer/0.1 Python/2.7.3
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE
Content-Type: text/html; charset=utf-8
Access-Control-Allow-Headers: Content-Type,*
Access-Control-Allow-Credentials: true
我做错了什么?
答案 0 :(得分:1)
您好,我认为您实际上是在提出交叉来源请求。
要启动跨源请求,浏览器会使用Origin HTTP标头发送请求。此标头的值是为页面提供服务的站点。
要允许该请求,它会在其响应中发送一个Access-Control-Allow-Origin标头。标题的值表示允许的源站点。
Access-Control-Allow-Origin: localhost:80
基本上你需要允许服务器端的选项请求发送回来 Access-Control-Allow-Origin标头
请仔细阅读以获得更好的想法
Cross domain POST query using Cross-Origin Resource Sharing getting no data back