簡體   English   中英

Express / NodeJS上的CORS問題,Internet Explorer無法提供服務

[英]CORS issue on express/NodeJS, services not available from Internet Explorer

我在Express / NodeJS上編寫了基於REST的服務。 我已經為CORS(跨源資源共享)實現編寫了代碼。 可以從chrome,firefox等瀏覽器中使用服務,但不能從Internet Explorer瀏覽器使用(我正在使用IE9,我檢查了IE-10,控制台中仍然有錯誤消息)

來自節點服務器端的來自route.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的錯誤

正如Bill所說,IE使用XDR。 您正在尋找的解決方案在這里: https : //github.com/jaubourg/ajaxHooks/blob/master/src/xdr.js

基本上,我在一個初始JS文件(在jQuery加載后)上有了該代碼,就可以解決問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM