Access-Control-Allow-Origin setting in NodeJS

The example shows setting CORS on NodeJS Express engine based web services.

var router = express.Router();
router.options('/', function(req, res, next){

res.setHeader('Access-Control-Allow-Origin', '*');

res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');

res.setHeader('Access-Control-Allow-Credentials', false);

res.setHeader('Access-Control-Max-Age', '86400'); // 24 hours

res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');



Add support for the options mentioned inside every service implementation. The * indicates that requests will be allowed from any originating service. Such a configuration should be used in Sandbox / Test mode only.

For production use it is recommended to allow requests from a specific domain only, as in with the below code.

res.setHeader('Access-Control-Allow-Origin', '*.mywebsite.com');