'CORS issues: The 'Access-Control-Allow-Origin' header mustn't contain multiple values

I want to allow my server to let two different domains read data without getting a CORS issue.

Therefore, I wrote the following code line (in node.js):

app.use(function(req, res, next){
   res.header("Access-Control-Allow-Origin", ["http://ServerA:3000", "http://ServerB:3000"]);
   res.header("Access-Control-Allow-Headers", "*");
   next();
});

However, when I sent the request by the browser I got the error:

The 'Access-Control-Allow-Origin' header contains multiple values 'http://ServerA:3000, http://ServerB:3000', but only one is allowed. Origin 'http://ServerB:3000' is therefore not allowed access.

My question is how to define 'Access-Control-Allow-Origin for more than one origin. I don't want to use '*' because it is too liberal.



Solution 1:[1]

You need to check your current origin with the ones that you have in the config:

let allowedOrigins = ["http://ServerA:3000", "http://ServerB:3000"]
let origin = req.headers.origin;
if (allowedOrigins.includes(origin)) {
    res.header("Access-Control-Allow-Origin", origin); // restrict it to the required domain
}

The header expects only one value of the origin, or a wildcard sign, that's why it's not working for you

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1