Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js

I'm trying to build a web server in node.js that will support cross-domain scripting, while still providing static files from a public directory. I'm using the express.js and am not really sure how to allow cross-domain scripting (Access-Control-Allow-Origin: *).

I saw this post, which I did not find helpful.

var express = require('express')   , app = express.createServer();  app.get('/', function (req, res, next) {     res.header("Access-Control-Allow-Origin", "*");     res.header("Access-Control-Allow-Headers", "X-Requested-With");     next(); });  app.configure(function () {     app.use(express.methodOverride());     app.use(express.bodyParser());     app.use(app.router); });  app.configure('development', function () {      app.use(express.static(__dirname + '/public'));     app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); });  app.configure('production', function () {       var oneYear = 31557600000;     //    app.use(express.static(__dirname + '/public', { maxAge: oneYear }));     app.use(express.static(__dirname + '/public'));     app.use(express.errorHandler()); });  app.listen(8888); console.log('express running at http://localhost:%d', 8888); 
like image 900
Guy Avatar asked Jun 24 '12 21:06

Guy


People also ask

How do I enable CORS origin in node JS?

Here is how you can allow a single domain access using CORS options: var corsOptions = { origin: 'http://localhost:8080', optionsSuccessStatus: 200 // For legacy browser support } app. use(cors(corsOptions)); If you configure the domain name in the origin - the server will allow CORS from the configured domain.

How do I enable CORS in Express JS?

Enabling CORS The easiest way to get CORS working in Express is by using the cors npm module. That's it. CORS is now enabled. The Access-Control-Allow-Origin header determines which origins are allowed to access server resources over CORS (the * wildcard allows access from any origin).


2 Answers

Check out the example from enable-cors.org:

In your ExpressJS app on node.js, do the following with your routes:

app.all('/', function(req, res, next) {   res.header("Access-Control-Allow-Origin", "*");   res.header("Access-Control-Allow-Headers", "X-Requested-With");   next();  });  app.get('/', function(req, res, next) {   // Handle the get for this route });  app.post('/', function(req, res, next) {  // Handle the post for this route }); 

The first call (app.all) should be made before all the other routes in your app (or at least the ones you want to be CORS enabled).

[Edit]

If you want the headers to show up for static files as well, try this (make sure it's before the call to use(express.static()):

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

I tested this with your code, and got the headers on assets from the public directory:

var express = require('express')   , app = express.createServer();  app.configure(function () {     app.use(express.methodOverride());     app.use(express.bodyParser());     app.use(function(req, res, next) {       res.header("Access-Control-Allow-Origin", "*");       res.header("Access-Control-Allow-Headers", "X-Requested-With");       next();     });     app.use(app.router); });  app.configure('development', function () {     app.use(express.static(__dirname + '/public'));     app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); });  app.configure('production', function () {     app.use(express.static(__dirname + '/public'));     app.use(express.errorHandler()); });  app.listen(8888); console.log('express running at http://localhost:%d', 8888); 

You could, of course, package the function up into a module so you can do something like

// cors.js  module.exports = function() {   return function(req, res, next) {     res.header("Access-Control-Allow-Origin", "*");     res.header("Access-Control-Allow-Headers", "X-Requested-With");     next();   }; }  // server.js  cors = require('./cors'); app.use(cors()); 
like image 148
Michelle Tilley Avatar answered Sep 22 '22 10:09

Michelle Tilley


Following @Michelle Tilley solution, apparently it didn't work for me at first. Not sure why, maybe I am using chrome and different version of node. After did some minor tweaks, it is working for me now.

app.all('*', function(req, res, next) {   res.header('Access-Control-Allow-Origin', '*');   res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');   res.header('Access-Control-Allow-Headers', 'Content-Type');   next(); }); 

In case someone facing similar issue as mine, this might be helpful.

like image 31
TonyTakeshi Avatar answered Sep 19 '22 10:09

TonyTakeshi