CORS for NodeJs Express

May 01, 2017

CORS stands for Cross-Origin Resource Sharing and it is what enables a web service to serve up requests to another web application invoking those requests through an http request. You can read more about CORS at Enable CORS. If you have a RESTful NodeJS Express web service that you want to expose to other web applications to consume it, you'll need to enable CORS.

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

Here's the same functionality but wrapped up in some middleware that allows CORS and offers more flexibility/customization. It's extremely simple and lightweight, here's the quick steps.

Start by installing the npm package for cors, invoke this command from a shell/terminal.

npm install cors --save

then you'll need to wire up the middleware to be used. On their github page it shows all the various options for customizing for specific routes and verbs. The default below will enable cors for all routes and verbs.

var express = require('express')
var cors = require('cors')
var app = express()