Allow multiple CORS domain in express js

前端 未结 4 809
予麋鹿
予麋鹿 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: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();
    })
    

提交回复
热议问题