backbonejs + cors和save()方法

时间:2012-12-05 16:22:07

标签: backbone.js save cors

我正在尝试执行POST抛出save方法。这是我的模特。

app.Models.Dummy = Backbone.Model.extend({
    initialize: function () {
        url = 'http://anotherdomain/Hello/';
    },
});

当我执行时:

    dummy.save({text : "greg"}, {
        success : function(){       
            console.log('Ok!');
        }, 
        error: function(){
            console.log('Error');
        }
    });

使用OPTIONS标头(代码200)触发请求,但永远不会触发POST请求。 但是当我执行时:

    $.ajax({
        type: 'POST',
        url: "http://anotherdomain/Hello/",
        data: {text:"greg"},
        success: function(r) { alert(r.Result) },
        dataType: "application/json"
    });

它有效!

我是否需要覆盖骨干网中的某些内容?

修改

请求是:

OPTIONS http://anotherdomain/Hello/ HTTP/1.1
Host: anotherdomain
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/17.0 Firefox/17.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
Origin: http://mydomain
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Pragma: no-cache
Cache-Control: no-cache

,回复是:

HTTP/1.1 200 OK
Cache-Control: private
Content-Length: 0
Server: Microsoft-IIS/7.5
Set-Cookie: ARRAffinity=611c389e4fd6c5d83202b700ce5627f6e0850faf0604f13c25903b4662919f36;Path=/;Domain=anotherdomain
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
X-Powered-By: ARR/2.5
X-Powered-By: ASP.NET
Date: Wed, 05 Dec 2012 18:44:27 GMT

1 个答案:

答案 0 :(得分:0)

这不是CORS的有效OPTIONS响应。响应需要包含告诉浏览器允许的标头。例如(取自MDN):

Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: X-PINGOTHER

我知道你说$ .ajax工作但基于这个CORS响应我怀疑这是准确的并建议你仔细检查。在幕后,骨干本身就是使用$ .ajax