How to add CORS functionality to your NodeJS web app

Published Dec 01, 2017

You can include a functionality to efficiently handle Cross domain requests. Known as CORS (Cross Origin Resource Sharing) it can be implemented on your NodeJS web application in the following two ways.

  1. Use cors npm module.
            - This is easier and faster way to enable CORS in your application. First, install cors module:
            # npm install --save cors

- Now that cors module is installed in your app, use it as middleware and you're done. All your requests are now CORS enabled:
        ## app.js
            var express = require('express');
            var cors = require('cors');
            var app = express();
 
            app.use(cors());

- You can also enable CORS on only a single request with the following code:
        ## app.js
        var express = require('express');
        var cors = require('cors');
        var app = express();
       
        app.get('/products/:id', cors(), function (req, res, next) {
            res.json({msg: 'This is CORS-enabled for a Single Route'});
        });

For more information you can refer to the documentation for cors module here: https://www.npmjs.com/package/cors

  1. You can achieve the same, without requiring any external module if you are fine adding a few extra lines in your code. Add the following code to enable CORS functionality:
            ## app.js
            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");
                next();
            });
Discover and read more posts from Robin G
get started