2

I have a REST based service written on Express/NodeJS . I have written code for CORS (Cross Origin Resource Sharing) Implementation . And services can be consumed from browsers like chrome, firefox etc.. but not from Internet explorer, (I am using IE9, I checked witrh IE-10,CORS error message is still there in console)

CODE FROM routes.js File on node server side

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);
...
}

Following is the code of config.jf file

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

};

And this is my server.js(app.js) file // Configuration

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);

The services cannot be obtained from IE. This is the first application I am doing in this stack,and my understanding is limited.please suggest a solution.

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" is the function that runs first, it alerts- Success while running on chrome and firefox, but alerts error from IE

Cœur
  • 37,241
  • 25
  • 195
  • 267
dany
  • 1,801
  • 7
  • 27
  • 40
  • IE9 uses an XDR request instead of the standard XHR request. jQuery by default doesn't support XDR, are you making the right kind of request? http://stackoverflow.com/questions/10232017/ie9-jquery-ajax-with-cors-returns-access-is-denied – Bill Oct 10 '12 at 06:13
  • Client side is done using BackboneJS. I added client side code also with my question.Please see the same. – dany Oct 10 '12 at 07:11
  • Are you trying to do this over an HTTPS connection? – tkone Oct 10 '12 at 16:16
  • No, Its HTTP connection. – dany Oct 11 '12 at 04:14

1 Answers1

0

As commented by Bill, IE uses XDR. The solution you are looking for is here: https://github.com/jaubourg/ajaxHooks/blob/master/src/xdr.js

Basically I have that code on one of my initial JS files (after jQuery is loaded) and that will do the trick.

Community
  • 1
  • 1