跨域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
从托管在另一个域骨干我的应用程序,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.
我的相关骨干code:
My relevant backbone code:
var newPostData = {
topic : "New Post",
body : "new body",
user_id : 1,
};
var newPostModel = new Post(newPostData);
this.model.create(newPostModel);
我甚至尝试过骑创建
方法和人工制造的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);
}
});
}
同样的错误。
我尝试了独立的GET上的jsfiddle以及(http://jsfiddle.net/X9cqh/5/)请求,但失败了,即使我的骨干应用程序可以使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?
推荐答案
该服务器还应该与下面的头回复preflight:
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屋!