Allow multiple CORS domain in express js

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


The value of Access-Control-Allow-Origin must be a string, not a list. So to make it dynamic you need to get the requesting origin from the Origin HTTP request header, check it against your array of authorized origins. If it's present, then add that origin as the value of the Access-Control-Allow-Origin header; otherwise, use a default value, which would prohibit unauthorized 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) {
  const origin = cors.origin.contains(req.header('origin').toLowerCase()) ? 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));