我正在使用此模块来处理cors请求 www.npmjs/package/cors 我需要限制除白名单之外的所有域
I am using this module to handle cors requests www.npmjs/package/cors I need to restrict all domains except whitelisted
从官方CORS模块示例中:
From official CORS module example:
var whitelist = ['example1', 'example2']; 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 = ['example1', 'example2']; 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.' }); });然后我从 http:// localhost:8080 通过发布到 app.post('/ products /:id'...)我希望它不应该执行,因为 http :// localhost:8080 不在白名单中,但实际上已经列入白名单。知道为什么以及如何解决这个问题吗?
Then I run test from localhost:8080 by posting to app.post('/products/:id'...) I expected it should not be executed because localhost:8080 is not whitelisted but actually it did. Any idea why and how to fix that?
我也确实添加了 cors(corsOptions)来观看,但这是在说-不可用
Also I didadd cors(corsOptions) to watch but it is saying - not available
推荐答案原因是 corsOptions 仍为未定义(实际上与 cors()),因为在启动期间会立即评估 cors(corsOptions)。
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.
更多推荐
Express CORS域白名单
发布评论