How To Enable Cors In Node.js Express

    Oct 20, 2018       by Pankaj Kumar
enable-cors-nodejs-express.jpg

In this article, I will explain you about Cross-origin resource sharing. Normally we can make http request with the same origin in our application. Means in the http request the domain and port must match to load the data. The restriction is there for security reasons. Whenever we want to load data from other origin then we need to perform some task while working with express framework of node.js application.

 

Implementing CORS

CORS is implimented through Access-Control-Allow-Origin header. In node.js express it is very easy to implement CORS. For that there is a npm package which is used to do the task with the command npm install cors over terminal. One cors is installed via terminal then use the cors in express app using below code:

app.use(require(cors)());

 

After making the above change in our express app, Once we make any request we will see a new header will return like below:

Access-Control-Allow-Origin: *

 

In the above code, The Access-Control-Allow-Origin header determines which origins are allowed to access server resources over CORS (the * wildcard allows access from all origin).

 

Enable CORS to specific routes

We will use cors in a specific routing

app.use('/user', require('cors')());

 

Restricting specific hosts

Suppose we have to restrict to a single origin, Can do by below code:

app.use(cors({  origin: 'http://specificip.com' }));

 

Configuring CORS w/ Dynamic Origin

 

 
var whitelist = ['http://example1.com', 'http://example2.com']
var corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
 

 

Conclusion

Adding CORS in Express is fast and easy, especially if we use the CORS library.

 

That’s all for now. Thank you for reading and I hope this article will be very helpful to understand how to  to enable cors in nodejs express.

Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.


WHAT'S NEW

Find other similar Articles here: