我有一个在 Express/NodeJS 上编写的基于 REST 的服务。我已经为 CORS (Cross Origin Resource Sharing) Implementation 编写了代码。并且可以从 chrome、firefox 等浏览器使用服务。但不能从 Internet Explorer 使用,(我使用的是 IE9,我检查了 IE-10,CORS 错误消息仍然存在于控制台中)
CODE FROM routes.js 文件在节点服务器端
var config = require('./config.js');
exports.setup = function (params) {
var controllers = params.controllers;
var app = params.app;
// CORS (Cross Origin Resource Sharing) Implementation
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Credentials", config.responseSettings.AccessControlAllowCredentials);
res.header("Access-Control-Allow-Origin", (req.headers.origin) ? req.headers.origin : config.responseSettings.AccessControlAllowOrigin);
res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : config.responseSettings.AccessControlAllowMethods);
next();
});
app.get('/', function(req, res) {
res.render('index', { title: 'Welcome })
});
function auth(req, res, next) {
if (req.session.UserId || (req.query.apikey && config.apikeys.indexOf(req.query.apikey) > -1)) {
next();
} else {
res.send(401);
}
}
app.get('/Session/:id?', controllers.SessionController.getSession);
app.post('/Session', controllers.SessionController.createSession);
app.del('/Session/:id', controllers.SessionController.deleteSession);
...
}
以下是 config.jf 文件的代码
module.exports = {
"db": {
"mongodb": "mongodb://admin:XYX123@localhost/xyx",
"username": "abc",
"password": "abc123",
"database": "abcdb",
"server": "localhost"
},
"cookiesecret": "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz",
"responseSettings": {
"AccessControlAllowOrigin": "*",
"AccessControlAllowHeaders": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version",
"AccessControlAllowMethods": "POST,GET,PUT,DELETE",
"AccessControlAllowCredentials": true
},
"apikeys": ['587c57365b54e8283fd6b1ac24acf29d', '4de04266bdd87410de698cfc33c55d68', '232c0252cee5e97148636ee2efd6ee94'], //only 1 is used now
};
这是我的 server.js(app.js) 文件 // 配置
app.configure(function () {
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({ // to set a time here only for session expire
secret: config.cookiesecret,
store: new MongoStore({ db: config.db.database, host: config.db.server, username: config.db.username, password: config.db.password })
}));
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function () {
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function () {
app.use(express.errorHandler());
});
// Routes
routes.setup({
'controllers': controllers,
'app': app
});
app.listen(process.env.port || 3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
无法从 IE 获取服务。这是我在这个堆栈中做的第一个应用程序,我的理解有限。请提出一个解决方案。
客户端在 Backbonejs 中完成:这是来自客户端的代码
define([
'config',
'jquery',
'underscore',
'backbone'
], function (config, $, _, Backbone) {
var SessionModel = Backbone.Model.extend({
urlRoot: config.BaseUrl + '/Session',
initialize: function () {
var that = this;
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
options.xhrFields = {
withCredentials: true
};
})
},
login: function (creds, callback) {
// Do a POST to /session and send the serialized form creds
this.save(creds, {
success: callback
});
},
logout: function (callback) {
// Do a DELETE to /session and clear the clientside data
var that = this;
this.destroy({
success: function (model, resp) {
model.clear()
model.id = null;
// Set auth to false to trigger a change:auth event
// The server also returns a new csrf token so that
// the user can relogin without refreshing the page
that.set({ auth: false });
callback();
}
});
},
getAuth: function (callback) {
// getAuth is wrapped around our router
// before we start any routers let us see if the user is valid
this.fetch({
//success: callback
success: function (req, res) {
//alert("success");
callback();
},
error: function (err) {
//alert("error");
callback();
}
});
}
});
return new SessionModel;
});
“getAuth”是首先运行的函数,它会发出警报——在 chrome 和 firefox 上运行时成功,但会从 IE 发出错误警报