6

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

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 (http://jsfiddle.net/X9cqh/5/) 上尝试了一个独立的 GET 请求,但是即使我的主干应用程序可以使 GET 请求正常,它也会失败。

在这一点上我完全一无所知。任何提示,指针,解决方案?

4

3 回答 3

6

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

Access-Control-Allow-Headers: Content-Type

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

于 2012-11-20T02:30:59.787 回答
1

添加“Content-Type”标头使您的 CORS 请求失败的原因是您的服务器设置错误。

如果客户端希望指定特定的标头或使用不寻常的 http 方法动词(例如 PUT),则浏览器将首先执行“预检”OPTIONS 调用以确保允许设置这些标头。您的服务器需要使用适当的标头响应此 OPTIONS 调用。如果您想确认这是问题所在,您会在 Chrome 开发人员工具或 firebug 的网络选项卡中看到选项调用。

您可能对我在这里更详细的回答感兴趣。

于 2012-12-20T12:07:38.377 回答
1

您的服务器设置有效。JSFiddle 显然不会发出 ajax 请求,但是您可以通过在 Chrome 控制台或 Safari 开发者控制台中输入以下四行来快速测试它是否有效:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://projectwhatup.us:5000/api/posts', false);
xhr.send();
xhr.responseText;

在此处输入图像描述

如果您使用不允许 CORS 的域尝试此操作,则会出错。

于 2012-11-20T02:07:12.313 回答