CORS Middleware Configuration for ExpressJS (using expressjs/cors)

JS
S
JavaScript

Inject the middleware, immediately after after calling the express instance (ie. const app = express()); The configuration will inject CORS middleware across all routes and contains a hardcoded whitelist for production and an allow all for dev mode.

1// app.js
2// npm install cors
3// var cors = require('cors')
4
5// Allow all options
6app.options("/*", (req, res, next) => {
7  res.header('Access-Control-Allow-Origin', '*');
8  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
9  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
10  res.send(200);
11});
12
13app.use(function(req,res,next){ req.headers.origin = req.headers.origin || req.headers.host; next(); })
14if(app.get('env') === 'production'){
15  console.log('CORS Enabled, PROD')
16  const whitelist = ['www.coderecipes.org','coderecipes.org','http://coderecipes.org', 'http://www.coderecipes.org', 'http://localhost:3232']
17  var corsOptions = {
18    origin: function (origin, callback) {
19      if (whitelist.indexOf(origin) !== -1) {
20        callback(null, true)
21      } else {
22        callback(new Error(`Not allowed by CORS ${origin}`));
23      }
24    }
25  }
26  app.use(cors(corsOptions));
27}
28else{
29  console.log('CORS Enabled, DEV')
30  app.use(cors());
31}

Created on 6/11/2017