【发布时间】:2012-12-20 13:24:21
【问题描述】:
我正在尝试为我的主干应用实现跨域设置。
我的服务器 (express.js) 允许跨域和凭据:
var allowCrossDomain = function(req, res, next) {
var allowedHost = [
'http://localhost:3001',
'http://localhost:7357'
];
if(allowedHost.indexOf(req.headers.origin) !== -1) {
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Origin', req.headers.origin)
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version');
next();
} else {
res.send({auth: false});
}
}
app.configure(function(){
....
app.use(allowCrossDomain);
....
});
我的客户端 (backbone.js) 也被配置为接受跨域:
define(["backbone", "jquery", "underscore"], function (BB, $, _) {
return BB.Model.extend({
idAttribute: "_id",
initialize: function () {
var that = this;
$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
options.crossDomain ={
crossDomain: true
};
options.xhrFields = {
withCredentials: true
};
});
}
});
});
现在当我测试我的代码时(比如说POST 请求),我有一个非常特殊的行为:
var contacts = new Contacts;
contacts.create({'name': 'my name'});
浏览器返回此消息:
选项 ... 404(未找到) jquery.js:8419
这完全让我感到困惑,因为主干不支持OPTIONS http 方法?
【问题讨论】:
-
OPTIONS 调用是预检请求:developer.mozilla.org/en-US/docs/HTTP/…
标签: ajax node.js backbone.js express cors