【发布时间】:2012-11-23 13:00:57
【问题描述】:
我正在尝试执行 POST 抛出保存方法。这是我的模型。
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
【问题讨论】:
-
完整的 OPTIONS 响应是什么?请注意,主干文档说有时 model.save() 会执行 PUT 而不是 POST,因此您的服务需要允许这样做
-
使用请求和响应编辑帖子。
-
2 年后,我也遇到了同样的情况。你解决了吗?我已经在我的 express 服务器上添加了标头,并且我已经在我的 Backbone.sync 中添加了 crossDomain 选项。但我似乎无法克服这一点。它只发生在骨干上。不是邮递员,也不是普通的 jQuery。
-
@RyanOre 不幸的是我不记得我了。我想我没有使用 sync () 但 post() 和 put() 有一些黑客......抱歉不能帮助你更多
-
实际上,@Greg 我通过在我的 Express 路由器上安装一个全局中间件来检查方法 OPTIONS,从而解决了我的问题。如果是,则它允许所有域。然后对于 POST 请求,我有一个单独的中间件来处理细节。所以对我来说,解决办法是让 OPTIONS 对所有人开放。
标签: backbone.js save cors