跨域XHR失败

xbo*_*nez 6 javascript xmlhttprequest cors backbone.js

我在一个域上托管了一个API,该域使用以下标头启用了CORS:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Max-Age: 1728000
Run Code Online (Sandbox Code Playgroud)

我可以从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.
Run Code Online (Sandbox Code Playgroud)

我的相关骨干代码:

var newPostData = {
    topic : "New Post",
    body : "new body",          
    user_id : 1,
};  

var newPostModel = new Post(newPostData);
this.model.create(newPostModel);
Run Code Online (Sandbox Code Playgroud)

我甚至尝试过度使用该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);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

同样的错误.

我在JSFiddle上尝试了一个独立的GET请求(http://jsfiddle.net/X9cqh/5/),但即使我的骨干应用程序可以使GET请求正常,也会失败.

在这一点上我完全无能为力.任何提示,指针,解决方案?

mon*_*sur 6

服务器还应使用以下标头回复预检:

Access-Control-Allow-Headers: Content-Type
Run Code Online (Sandbox Code Playgroud)

这是必要的,因为内容类型是application/json,它超出了CORS规范(http://www.w3.org/TR/cors/)中定义的可接受值.