Allow multiple CORS domain in express js

How to allow multiple domains for CORS in a simplified form.

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 originas an array of domains, and I want to enable CORS for all domains in the source array, I would have something like this -

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

But then the problem is that the code below does 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 to make res.headertake an array of domains through cors.origin?

+4
source share
3 answers

cors-module: https://www.npmjs.org/package/cors - CORS " -Section

+9

, . "Access-Control-Allow-Origin" . , http. . , , API.

. , .

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

app.all('*', function(req, res, next) {
                var origin = cors.origin.indexOf(req.header('host').toLowerCase()) > -1 ? req.headers.origin : cors.default;
                res.header("Access-Control-Allow-Origin", origin);
                res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                next();
            });
+10

In fact, the Access-Control-Allow-Origin header should be the same value as the Origin header if you want to allow it.

So base your code just

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



app.all('*', function(req, res, next) {
            let origin = req.headers.origin;
            if(cors.origin.indexOf(origin) >= 0){
                res.header("Access-Control-Allow-Origin", origin);
            }         
            res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            next();
        });
+1
source

All Articles