Search code examples
javascriptnode.jsexpressbackend

Why do the CORS settings for my Express.js backend not work?


I am trying to set CORS for my Express.js backend. Since I have a local and a remote version of the front end I want to allow a couple of URLS access to the backend. I have tried to use "*" and var cors = require('cors') app.use(cors()) but I get

Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true.

I have tried using the dynamic settings for cors(), but there were no examples how to use it with Express's routes. I am now trying to create my own white list check with the code below but now I am getting

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5000' is therefore not allowed access. The response had HTTP status code 500.

What am I doing wrong?

UPDATE: It looks like the if statement is blocking the headers from being added so I tried to remove it to see what is happening with res.header('Access-Control-Allow-Origin', req.get("origin")); It is now giving me

Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials.

var whiteList = {
    "http://localhost:5000": true,
    "https://example-url.herokuapp.com": true
};
var allowCrossDomain = function(req, res, next) {    
        if(whiteList[req.get('Origin')]){            
            res.header('Access-Control-Allow-Credentials', true);
            res.header('Access-Control-Allow-Origin', req.get('Origin'));
            res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
            res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, Origin, Accept');        
            next();
        } 
};
app.use(allowCrossDomain);

Solution

  • This ultimately came down to a spelling/understanding error. I was trying to get the request origin by using req.headers.Origin. Turns out there is no 'Origin' in headers, I had to use req.headers.origin instead. The code below will work, and let you use multiple URLs for CORS, it does not yet easily handle something like http://localhost:5000/route or a situation where the provided origin isn't in the list.

    var whiteList = {
        "http://localhost:5000": true,
        "https://example-url.herokuapp.com": true
    };
    var allowCrossDomain = function(req, res, next) {    
            if(whiteList[req.headers.origin]){            
                res.header('Access-Control-Allow-Credentials', true);
                res.header('Access-Control-Allow-Origin', req.headers.origin);
                res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
                res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, Origin, Accept');        
                next();
            } 
    };
    app.use(allowCrossDomain);