Allow multiple CORS domain in express js Allow multiple CORS domain in express js express express

Allow multiple CORS domain in express js


I would recommend the cors-module: https://www.npmjs.org/package/corsIt does this kind of stuff for you - check the "Configuring CORS w/ Dynamic Origin"-Section


Lets understand how this header works. "Access-Control-Allow-Origin" accepts only a string. So to make it dynamic you need to get the requesting host from the http header. Check it against your array of authorised domains. If it's present then add that as a value to the header, else adding a default value will prohibit unauthorised domains from accessing the API.

There is no native implementation for this. You can do it yourself using the code below.

cors: {            origin: ["www.one.com","www.two.com","www.three.com"],            default: "www.one.com"        }app.all('*', function(req, res, next) {                var origin = cors.origin.indexOf(req.header('origin').toLowerCase()) > -1 ? req.headers.origin : cors.default;                res.header("Access-Control-Allow-Origin", origin);                res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");                next();            });


Using Node, cors middleware, make sure you leave the / off the url, OR ELSE cors could fail if the url in the browser is displayed without it. I.e.

var corsOptions = {origin: ["http://www.example.com/","http://localhost:3000"],optionsSuccessStatus: 200 // For legacy browser support}app.use(cors(corsOptions));

Failed and would give me the cors error because the browser would display/read the url as http://www.example.com, where below worked and is more inclusive and should work for http://www.example.com and anything beyond that, i.e. http://www.example.com/ or http://www.example.com/blogs/1, etc

var corsOptions = {origin: ["http://www.example.com","http://localhost:3000"],optionsSuccessStatus: 200 // For legacy browser support}app.use(cors(corsOptions));