Check out an example from enable-cors.org :
In an ExpressJS application on node.js, follow these 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) {
The first call ( app.all ) must be made before all other routes in your application (or at least the ones you want to enable CORS).
[change]
If you want the headers to appear for static files as well, try this (make sure before calling 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 checked this with your code and got the asset headers 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 in a module so that you could 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());