How to enable CORS for multiple domains in Node.js
Today we’ll show you how to enable CORS for multiple domains in Node.js. In the previous article we learned about enabling the CORS for all or single domains in Node.js. But in this article we will allow multiple domains/origins to access resources.
Enable Access-Control-Allow-Origin for multiple domains in node js, Allow multiple CORS domain in express js, Allowing Multiple Cors In Node Express, node.js Enable Access Control Allow Origin for multiple domains or origin.
Checkout more articles on Node.js
In this article, we’ll allow multiple origins using cors npm package. If you don’t know how to use the cors package in Node.js then please follow the link: Enable CORS using npm package.
Enable CORS for multiple origins
The cors npm package provides the option to write the function for origin
value. Which will help us to enable CORS for multiple domains.
If you have a list of the allowed origins or domains then write the following code to enable CORS.
1 2 3 4 5 6 7 8 9 10 11 12 13 | var allowedDomains = ['http://yourdomain.com', 'http://localhost:3000']; app.use(cors({ origin: function (origin, callback) { // bypass the requests with no origin (like curl requests, mobile apps, etc ) if (!origin) return callback(null, true); if (allowedDomains.indexOf(origin) === -1) { var msg = `This site ${origin} does not have an access. Only specific domains are allowed to access it.`; return callback(new Error(msg), false); } return callback(null, true); } })); |
That’s all you need to enable CORS for multiple domains in Node.js.
Thank you for reading. Happy Coding!