I'm trying to allow CORS in node.js but the problem is that I can't set * to Access-Control-Allow-Origin if Access-Control-Allow-Credentials is set.
Also the specification said I can't do an array or comma separated value for Access-Control-Allow-Origin and the suggested method would be to do something similar to this Access-Control-Allow-Origin Multiple Origin Domains?
But I can't seem to do this way in node.js
["http://mydomain.com:9001", "http://mydomain.com:5001"].map(function(domain) {
res.setHeader( "Access-Control-Allow-Origin", domain );
});
res.header( "Access-Control-Allow-Credentials", true );
The problem here is that it's bein override by the last value in the array, so the header will be set to res.setHeader( "Access-Control-Allow-Origin", "http://mydomain.com:5001" );
Error from the client browser:
XMLHttpRequest cannot load http://mydomain.com:9090/api/sync. The 'Access-Control-Allow-Origin' header has a value 'http://mydomain.com:5001' that is not equal to the supplied origin. Origin 'http://mydomain.com:9001' is therefore not allowed access.
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. As I am a total Node.js and web noob in general I would appreciate any comments to this answer. Also, this would probably defeat the purpose with restricting what origins to accept and is probably horrible to use in production.
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.
Check your whitelist against what your req.headers.origin e.g.
var origins = ['a.com', 'b.com', 'c.com', 'boobies.com'];
for(var i=0;i<origins.length;i++){
var origin = origins[i];
if(req.headers.origin.indexOf(origin) > -1){
res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
return;
}
// else, tough cookies.
}
Enjoy.
Here's a simple middleware function to serve up the correct CORS header from a whitelist. Setting this near the top of your express app will allow all your routes to set the proper header from the whitelist before serving up content.
app.use(function(req, res, next){
var whitelist = ['localhost:4000', 'localhost:3000', 'anydomain.com']
var host = req.get('host');
whitelist.forEach(function(val, key){
if (host.indexOf(val) > -1){
res.setHeader('Access-Control-Allow-Origin', host);
}
})
next();
});