gpt4 book ai didi

javascript - express/NodeJS 上的 CORS 问题,Internet Explorer 不提供服务

转载 作者:行者123 更新时间:2023-11-30 06:39:06 25 4
gpt4 key购买 nike

我有一个用 Express/NodeJS 编写的基于 REST 的服务。我写了代码CORS(跨源资源共享)实现。并且服务可以从 chrome、firefox 等浏览器使用。但不能从 Internet Explorer 使用,(我使用的是 IE9,我检查了 IE-10,控制台中仍然存在 CORS 错误消息)

代码来自 Node 服务器端的 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 获取服务。这是我在这个堆栈中做的第一个应用程序,我的理解是有限的。请提出解决方案。

Client side is done in Backbonejs:This is the code from client-side

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 发出错误警报

最佳答案

正如 Bill 评论的那样, IE 使用 XDR。您正在寻找的解决方案在这里:https://github.com/jaubourg/ajaxHooks/blob/master/src/xdr.js

基本上,我在我的一个初始 JS 文件(加载 jQuery 之后)中有该代码,这将起到作用。

关于javascript - express/NodeJS 上的 CORS 问题,Internet Explorer 不提供服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12812973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com