Enable CORS in NodeJS (ExpressJS) With and Without CORS NPM

Article Contents

How To Enable & Use CORS in NodeJS (ExpressJS) With and Without CORS NPM?

Hello Developers, Continuing our NodeJS Tutorials Series and MEAN Stack Development Tutorials Series, In this How-To Guide, we are going to learn about Cross-Origin Resource Sharing CORS in NodeJS. So Let’s start with the following Question.

What is CORS and Why Do You Need CORS in NodeJS (ExpressJS)?

CORS Stands For Cross-Origin Resource Sharing in simple words cross-domain requests.

Modern Web App Developers Encounter this problem when they want to use resources from more than one domain and it becomes more complex when building Modern Web Applications which use CDNs, Complex APIs, and Services hosted on multiple domains and They encounter CORS Error due to Same Origin Policy restrictions and to overcome this problem they need to bypass Same Origin Policy restrictions.

Developers who are working with Nodejs and ExpressJS may need to expose the resources of your application to codes running on other domains. CORS is also recommended by  The World Wide Web Consortium (W3C) which has been implemented by Modern browsers such as chrome etc: https://www.w3.org/TR/cors/

CORS provides a method or procedure to use resources across domains using HTTP headers for a handshake that vets the domain making the request as an allowed domain.

DOM Elements Allowed For Cross-Origin Sharing:

  • Images with <img> tag.
  • Media Files with <audio> and <video> tags.
  • Plugins with the <object>, <embed> and <applet> tags.
  • Fonts with the @font-face method.
  • Any content or URI loaded with the <frame> and <iframe> tags. Note that the X-Frame-Options header can prevent cross-origin interaction between frames.
  • CSS with the <link rel=”stylesheet” href=”…”> tag.
  • JavaScript with the <script src=”…”></script> tag.
See also  Welcome to Stackfame.com

and Everything else is restricted by same origin policy.

How to Enable CORS on Node JS (ExpressJS)?

How to Enable CORS on Node JS (ExpressJS) without using any Module?

By using Header code to set the header in Nodejs:

res.header("Access-Control-Allow-Origin", "*");
using it as middleware as follows:
 
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();
});
if you want to use it for  resource file:
 
app.get('/get-file', function(req, res){
var myFile = __dirname + '/ExampleFile.zip';
res.download(myFile);
});

and the overall file will look like this:

var express = require('express');
var app = express();
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();
});
app.get('/', function (req, res) {
var itShares = {
"Symbols": [
"infy",
"wipro",
"heg" ,
"techmahindra"
]
};
res.json(itShares );
});
app.get('/get-file', function(req, res){
var file = __dirname + '/companyDataFile.zip';
res.download(file);
});
app.get('/**', function(req, res) {
res.send(invalidRequest(), 400);
});
var port = process.env.PORT || 3000;
app.listen(port, function() {
console.log("Listening on " + port);
});

To secure CORS you should consider defining domain like this:

app.get('/get-file', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://www.otherdomain.com");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});

How to Enable CORS on Node JS (ExpressJS) without using CORS NPM?

if you don’t want to all the complex work by yourself then you can use CORS NPM, Which makes your work lot easier.

Install CORS NPM by Command:
npm install cors --save

CORS offers flexible and Easier Way to deal and it offers a lot  of options, some are mentioned below:

Default Method:
 {
"origin": "*",
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"preflightContinue": false
}

Options:

  • Origin
  • Methods
  • allowedHeaders
  • exposedHeaders
  • credentials
  • maxAge
  • preflightContinue

To know more about all the details of these options go to https://www.npmjs.com/package/cors

How To Use CORS NPM with Examples:

Below example defines a GET request for route /user/:id. CORS is enabled for all origins and configures the app uses CORS for all routes.

var express = require('express')
, cors = require('cors')
, app = express();
app.use(cors()); // use CORS for all requests and all routes
app.get('/user/:id', function(req, res, next){
res.json({msg: 'response message'});
});

Allow CORS for Dynamic Origins for a Specific Route in Nodejs (ExpressJS)

 

var express = require('express')
, cors = require('cors')
, app = express();
// specify the allowed domains and set corsOptions to check them
var whitelist = ['http://domain.com','http://otherdomain.com'];
var corsOptions = {
origin: function(origin, callback){
var originWhitelisted = whitelist.indexOf(origin) !== -1;
callback(null, originWhitelisted);
}
};
// add corsOptions to the route /product/:id for a GET request
app.get('/user/:id', cors(corsOptions), function(req, res, next)
{
res.json({msg: 'response message'});
}); That's it, guys. Also, check out our other amazing articles:

How To Limit characters Displayed in Text with AngularJS

See also  Welcome to Stackfame.com

How to Update Node.JS to Latest Version (Linux, Ubuntu, OSX, Windows, Others)

 


		

2 thoughts on “Enable CORS in NodeJS (ExpressJS) With and Without CORS NPM”

Leave a Comment