Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
69
rated 0 times [  70] [ 1]  / answers: 1 / hits: 75405  / 10 Years ago, tue, november 18, 2014, 12:00:00

How do I allow multiple domains for CORS in express in a simplified way.



I have



 cors: {
origin: www.one.com;
}

app.all('*', function(req, res, next) {
res.header(Access-Control-Allow-Origin, cors.origin);
res.header(Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept);
next();
});


This works when there is only one domain mentioned in origin



But if I want to have origin as an array of domains and I want to allow CORS for all the domains in the origin array, I would have something like this -



cors: {
origin: [www.one.com,www.two.com,www.three.com];
}


But then the problem is this below code would not work -



app.all('*', function(req, res, next) {
res.header(Access-Control-Allow-Origin, cors.origin);
res.header(Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept);
next();
});


How do I make res.header take an array of domains via cors.origin ?


More From » node.js

 Answers
80

I would recommend the cors-module: https://www.npmjs.org/package/cors
It does this kind of stuff for you - check the Configuring CORS w/ Dynamic Origin-Section


[#68780] Friday, November 14, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dominiquezachariahh

Total Points: 343
Total Questions: 81
Total Answers: 106

Location: Monaco
Member since Fri, Sep 24, 2021
3 Years ago
;