Express CORS域白名单 [英] Express CORS domain whitelist
问题描述
我正在使用此模块来处理cors请求 https://www.npmjs.com/package/cors
我需要限制除白名单之外的所有域
I am using this module to handle cors requests https://www.npmjs.com/package/cors I need to restrict all domains except whitelisted
从官方CORS模块示例中:
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.' });
});
然后我从 http:// localhost:8080 $运行测试c $ c>通过发布到
app.post('/ products /:id'...)
我希望它不应该执行,因为 http :// localhost:8080
不在白名单中,但实际上已经列入白名单。知道为什么以及如何解决这个问题吗?
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?
我也确实添加了 cors(corsOptions)
来观看,但这是在说-不可用
Also I didadd cors(corsOptions)
to watch but it is saying - not available
推荐答案
原因是 cors(corsOptions)
时,> 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域白名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!