Express CORS domain whitelist

2019-09-05 13:52发布

问题:

I am using this module to handle cors requests https://www.npmjs.com/package/cors I need to restrict all domains except whitelisted

From official CORS module example:

var whitelist = ['http://example1.com', 'http://example2.com'];
var corsOptions = {
  origin: function(origin, callback){
    var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
    callback(null, originIsWhitelisted);
  }
};

app.get('/products/:id', cors(corsOptions), function(req, res, next){
  res.json({msg: 'This is CORS-enabled for a whitelisted domain.'});
});

Which I have changed to this to make it work:

var origin;
var corsOptions;
app.all('*', function (req, res, next) {
    origin = req.get('origin');
    var whitelist = ['http://example1.com', 'http://example2.com'];
    corsOptions = {
        origin: function (origin, callback) {
            var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
            callback(null, originIsWhitelisted);
        }
    };
    next();
});
app.post('/products/:id', cors(corsOptions), function (req, res, next) {
    res.json({ msg: 'This is CORS-enabled for a whitelisted domain.' });
});

Then I run test from http://localhost:8080 by posting to app.post('/products/:id'...) I expected it should not be executed because http://localhost:8080 is not whitelisted but actually it did. Any idea why and how to fix that?

Also I didadd cors(corsOptions) to watch but it is saying - not available

回答1:

The reason is that corsOptions is still undefined when cors(corsOptions) is called (effectively the same as cors()) since cors(corsOptions) is evaluated immediately during startup.