简体   繁体   English

跨域XHR失败

[英]Cross domain XHR failing

I have an API hosted on one domain that has CORS enabled with the following headers: 我在一个域上托管了一个API,该域使用以下标头启用了CORS:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Max-Age: 1728000

I am able to make a GET or POST request from hackst.com and it works fine. 我可以从hackst.com发出GET或POST请求,它运行正常。 Link: http://hackst.com/#w3SbV 链接: http//hackst.com/#w3SbV

From my backbone app hosted on another domain, GET requests work fine. 从我在另一个域上托管的骨干应用程序,GET请求工作正常。 But when I try to create and save a new model (ie make a POST request), it fails with the following error: 但是当我尝试创建并保存新模型(即发出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.

My relevant backbone code: 我的相关骨干代码:

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

var newPostModel = new Post(newPostData);
this.model.create(newPostModel);

I even tried over-riding the create method and making a POST request manually like this: 我甚至尝试过度使用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);
        }
    });
}

Same error. 同样的错误。

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

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

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

Your sever setup works. 您的服务器设置有效。 JSFiddle apparently does not make the ajax requests, but you can quickly test that it works by entering these four lines into Chrome console or Safari developer console: JSFiddle显然不会发出ajax请求,但你可以通过在Chrome控制台或Safari开发者控制台中输入这四行来快速测试它的工作原理:

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

在此输入图像描述

If you try this with a domain that does not allow CORS, it will error out. 如果您尝试使用不允许CORS的域,则会出错。

The reason that adding a 'Content-Type' header makes your CORS request fail is because your server is set up wrongly. 添加“Content-Type”标头会导致CORS请求失败的原因是您的服务器设置错误。

If the client wishes to specify particular headers or use an unusual http method verb (eg PUT), then the browser will first do a 'preflight' OPTIONS call to ensure that it is allowed to set those headers. 如果客户端希望指定特定标头或使用不常见的http方法动词(例如PUT),则浏览器将首先执行“预检”OPTIONS调用以确保允许设置这些标头。 Your server needs to respond to this OPTIONS call with the appropriate headers. 您的服务器需要使用适当的标头响应此OPTIONS调用。 You'll see that options call in the network tab of the Chrome developer tools or firebug if you want to confirm that this is what the problem is. 如果您想确认这就是问题所在,您会在Chrome开发者工具或firebug的网络标签中看到这些选项。

You may be interested in my more detailed answer here . 你可能有兴趣在我的更详细的解答这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM