跨域 XHR 失败 [英] Cross domain XHR failing
问题描述
我在一个域上托管了一个 API,该域启用了带有以下标头的 CORS:
I have an API hosted on one domain that has CORS enabled with the following headers:
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Max-Age: 1728000
我可以从 hackst.com 发出 GET 或 POST 请求,并且工作正常.链接:http://hackst.com/#w3SbV
I am able to make a GET or POST request from hackst.com and it works fine. Link: http://hackst.com/#w3SbV
从我在另一个域上托管的主干应用程序,GET 请求工作正常.但是当我尝试创建并保存新模型(即发出 POST 请求)时,它失败并显示以下错误:
From my backbone app hosted on another domain, GET requests work fine. But when I try to create and save a new model (i.e. make a POST request), it fails with the following error:
Failed to load resource: the server responded with a status of 501 (Not Implemented) http://projectwhatup.us:5000/api/posts
XMLHttpRequest cannot load http://projectwhatup.us:5000/api/posts. Origin http://ayush.projectwhatup.us is not allowed by Access-Control-Allow-Origin.
我的相关主干代码:
var newPostData = {
topic : "New Post",
body : "new body",
user_id : 1,
};
var newPostModel = new Post(newPostData);
this.model.create(newPostModel);
我什至尝试覆盖 create
方法并像这样手动发出 POST 请求:
I even tried over-riding the create
method and making a POST request manually like this:
create : function(data) {
console.log('overriden create');
$.ajax({
"url" : this.url,
"async" : true,
"beforeSend" : function(obj){
console.log(obj);
},
"contentType" : 'application/json',
//"crossDomain" : true, // uncommenting this doesnt help either
"headers" : {
},
"dataType" : 'json',
"type" : 'POST',
"data" : JSON.stringify(data),
"error" : function(err){
console.log('new post creation failed');
console.log(err);
},
"success" : function(resp){
console.log('new post created');
console.log(resp);
}
});
}
同样的错误.
我也在 JSFiddle (http://jsfiddle.net/X9cqh/5/) 上尝试了一个独立的 GET 请求,但即使我的主干应用程序可以使 GET 请求正常,但还是失败了.
I tried a stand-alone GET request on JSFiddle as well (http://jsfiddle.net/X9cqh/5/), but that fails even though my backbone app can make the GET request fine.
我在这一点上完全一无所知.任何提示、指示、解决方案?
I'm completely clueless at this point. Any hints, pointers, solutions?
推荐答案
服务器还应使用以下标题回复预检:
The server should also reply to the preflight with the following header:
Access-Control-Allow-Headers: Content-Type
这是必要的,因为内容类型是 application/json,这超出了 CORS 规范 (http://www.w3.org/TR/cors/) 中定义的可接受值.
This is necessary because the content type is application/json, which is outside the acceptable values defined in the CORS spec (http://www.w3.org/TR/cors/).
这篇关于跨域 XHR 失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!