Allow multiple CORS domain in express js

前端 未结 4 805
予麋鹿
予麋鹿 2020-12-15 22:00

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

I have

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

    app.all(\'*\', f         


        
相关标签:
4条回答
  • 2020-12-15 22:30

    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

    0 讨论(0)
  • 2020-12-15 22:31

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

    So base on 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();
            });
    
    0 讨论(0)
  • 2020-12-15 22:39

    Lets understand how this header works. "Access-Control-Allow-Origin" accepts only a string. So to make it dynamic you need to get the requesting host from the http header. Check it against your array of authorised domains. If it's present then add that as a value to the header, else adding a default value will prohibit unauthorised domains from accessing the API.

    There is no native implementation for this. You can do it yourself using the code below.

    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('origin').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();
                });
    
    0 讨论(0)
  • 2020-12-15 22:44

    Hi i want to share my solution: !!! These code works if you are using a remote server and developing on localhost (webpack or another dev environment) Cheers!!

    let ALLOWED_ORIGINS = ["http://serverabc.com", "http://localhost:8080"];
    app.use((req, res, next) => {
        let origin = req.headers.origin;
        let theOrigin = (ALLOWED_ORIGINS.indexOf(origin) >= 0) ? origin : ALLOWED_ORIGINS[0];
        res.header("Access-Control-Allow-Origin", theOrigin);
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    
        next();
    })
    
    0 讨论(0)
提交回复
热议问题