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.
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.
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.
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.
Simply add a header to your HttpServletResponse by calling addHeader : response. addHeader("Access-Control-Allow-Origin", "*");
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With