How to enable CORS in Nodejs

Node.js is an open-source, cross-platform JavaScript runtime environment for developing a wide variety of tools and applications. Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served.

This article expains the details to enable CORS in Nodejs.

As the first step check whether cors module is installed for this application and install it if its not installed.

#npm i cors

Then open the file src/config/express.ts inside node application folder and update the following lines.

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

Here we have to replace "DOMAIN" with the domain name that we need to enable the access. We can use the wild card '*' in-order to allow any domain. Please note that enabling all domains is not a secure practise for production environments.

Leave a Reply

Your email address will not be published. Required fields are marked *