我有一個API託管在具有與下列頭啓用CORS一個域名:跨域XHR遇事
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請求)時,出現以下錯誤:
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請求,如下所示:
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上也嘗試了一個獨立的GET請求(http://jsfiddle.net/X9cqh/5/),但即使我的骨幹應用程序可以使GET請求正常也失敗。
在這一點上,我完全無能爲力。任何提示,指針,解決方案?
看着[hurl.it(http://hurl.it/hurls/1330531e4f6c2b80fe278890b412cb50c3e4857c/432866d6c733527ea02f6436de63cbfac1a9ccc5)HEAD請求到服務器,它看起來像CORS只對'支持HTTP:// ayush.projectwhatup.us' – teddybeard
但是hackst.com的請求如何通過? – xbonez
這是因爲請求不是由您的Web瀏覽器進行的。類似Hurl.it,當你創建一個黑客。com請求,它由服務器在後端執行,然後在Web瀏覽器中顯示結果。 – teddybeard