Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 880
CrazySynthax Avatar asked Jan 28 '17 13:01

CrazySynthax


People also ask

How do I fix not allowed by Access-Control allow origin?

There Are Two Approaches to Getting It Right.Use a reverse proxy server or WSGI server(such as Nginx or Apache) to proxy requests to your resource and handle the OPTIONS method in the proxy. Add support for handling the OPTIONS method in the resource's code.

Does the Access-Control allow Origin header contains multiple values?

The 'Access-Control-Allow-Origin' header contains multiple values 'http://127.0.0.1:9000, http://127.0.0.1:9000', but only one is allowed. Origin 'http://127.0.0.1:9000' is therefore not allowed access. Fiddler shows me that there are indeed two header entries in the get request after a successful options request.

How do you fix a CORS problem?

To get rid of a CORS error, you can download a browser extension like CORS Unblock ↗. The extension appends Access-Control-Allow-Origin: * to every HTTP response when it is enabled. It can also add custom Access-Control-Allow-Origin and Access-Control-Allow-Methods headers to the responses.

How do I allow CORS Access-Control allow origin?

Simply add a header to your HttpServletResponse by calling addHeader : response. addHeader("Access-Control-Allow-Origin", "*");


1 Answers

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

like image 88
Vsevolod Goloviznin Avatar answered Nov 15 '22 22:11

Vsevolod Goloviznin