Express CORS domain whitelist

£可爱£侵袭症+ 提交于 2019-12-24 16:35:16

问题


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.



来源:https://stackoverflow.com/questions/36393256/express-cors-domain-whitelist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!