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);
Try to this cors npm modules.
This module provides many features to fine tune cors setting such as domain whitelisting, enabling cors for specific apis etc.
I use this:
this code assumes that your controllers are located in the controllers directory. each file in this directory should be something like this:
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.
In case someone facing similar issue as mine, this might be helpful.
Recommend using the cors express module. This allows you to whitelist domains, allow/restrict domains specifically to routes, etc.,
One additional step I needed to take was to switch my URL from
http://localhost
tohttp://127.0.0.0
You must set
Access-Control-Allow-Credentials: true
, if you want to use "cookie" via "Credentials"