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.
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
app}) //Allows access to single route
Thanks.
happy coding :) ...
Great article ... Thanks for sharing
ReplyDeleteNice
ReplyDelete