Last Updated: December 12, 2017
·
272
· nodejsagency

How to add CORS functionality to your NodeJS web app

  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
  2. 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());

2 - 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

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();
});