Enable Access-Control-Allow-Origin for multiple domains in Node.js
Not sure if this is to late but I solved it by setting:
res.setHeader("Access-Control-Allow-Origin", req.headers.origin);
This will simply allow every connection as the headers.origin will be sent with every query.
You may want to write a function to check if the req.headers.origin is a whitelisted domain (from a hardcoded array) and the simply return this domain if it exists in the array.
Here is what I use in my express application to allow multiple origins
app.use((req, res, next) => {
const allowedOrigins = ['http://127.0.0.1:8020', 'http://localhost:8020', 'http://127.0.0.1:9000', 'http://localhost:9000'];
const origin = req.headers.origin;
if (allowedOrigins.includes(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
}
//res.header('Access-Control-Allow-Origin', 'http://127.0.0.1:8020');
res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.header('Access-Control-Allow-Credentials', true);
return next();
});