Skip to main content

CORS in NodeJS

CORS in NodeJS

What is CORS?
Cross origin Resource Sharing is a mechanism of sharing the resources like images, API, styles, fonts, audio, video, etc from another domain.

By default any browser has same-origin policy, which restricts the browser to access all content from its own domain. But, what if browser want to excess data from other domain?

For Example: If domain1.com wants to call API which is defined in domain2.com, then domain1.com has to by pass its same-origin policy to cross-origin policy.

Why CORS?

CORS defines who can access what, and thus securing the domain. It can be dangerous if CORS enables to access API to everyone.

How to use it in Nodejs?

Method 1:

const app = express();
app.use(function (req, res, next) {
     res.header("Access-Control-Allow-Origin", "*"); //Allow access to everyone
     res.header("Access-Control-Allow-Origin", "http://domain1.com"); //Allow access to domain1
});

Method 2:

using Nodejs cors module
Do npm install cors

app.use(cors()) //Allow access to everyone



app.get('route1', cors(), function () {}) //Allows access to single route

Thanks.

happy coding :) ...

Comments

Post a Comment