Saturday, April 13, 2013

Node.js Express JS and CORS (Cross Origin Resource Sharing)

Foreword

It seems that by default web browsers don't allow Cross Origin Resource Sharing which means that if a request is done from for example www.domain1.com to a resource on www.domain2.com it is treated as security issue. This is also the case if different ports are used with the same domain. So for example if your Angularjs application is running on localhost port 8000 and you are connecting on to an Express JS server that is running on localhost port 3000 it won't work. It's actually quite hard to debug as in Firefox the request will be displayed as red but there is no error message that is showing up explaining why the request is not working. Also the http status is 0 which is quite confusing. When however debugging the request with the Chrome browser there will be a message that says that XMLHttpRequests are forbidden.

One additional thing there is to say is that Chrome also does not accept such requests if the html file is opened directly in the browser. A web server will be required to execute the request (file:// is not working with all browsers, http:// is working).

More information on the issue can be found here.

Configuring Express JS

To solve this issue it is necessary to configure the Express JS server to explicitly allow such connections. To achieve this I have added following to the configuration of Express JS.
var express = require('express');

var app = express();

app.all('/*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
});

...
  • The first header setting is allowing access from different origins. "*" means that all origins will be accepted but it is also possible to set explicit origins.
  • The second header setting is necessary because Angular is adding a "X-Requested-With" XMLHttpRequest header when opening a connection to a resource.

No comments:

Post a Comment