节点表达和路由 [英] Node express cors and routes
问题描述
我使用CORS https://www.npmjs.com/package/cors 允许 whitedomain
列表。
I am using CORS https://www.npmjs.com/package/cors to allow whitedomain
list.
var whitelist = ['http://example1.com', 'http://example2.com'];
var corsOptions = {
origin: function(origin, callback){
var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
callback(null, originIsWhitelisted);
}
};
app.post('/products/:id', cors(corsOptions), function (req, res, next) {
console.log(0);
res.json({ msg: 'This is CORS-enabled for a whitelisted domain.' });
});
如果非whitedomain
没有访问控制允许原因
这是罚款,但同时我可以看到在调试,行 res.json({ msg:'这是为白名单域启用的CORS。'});
和 console.log(0);
code> console.log(0); c>在服务器端的控制台打印 0
这是我不想
In case of non whitedomain
the server returns No 'Access-Control-Allow-Origin'
which is fine but at the same time I can see on debug that the lines res.json({ msg: 'This is CORS-enabled for a whitelisted domain.' });
and console.log(0);
still gets executed - console.log(0);
printed 0
in console on server side which is something I do not wan't in that case.
所以让我们说如果是扭动到数据库:
So lets say if is writhing to database:
app.post('/products/:id', cors(corsOptions), function (req, res, next) {
writeToDatabase();
res.json({ msg: 'This is CORS-enabled for a whitelisted domain.' });
});
这样 writeToDatabase();
执行。但是我想避免这种情况,因为在非白名单
域中,我不需要在数据库中写任何东西。
This way writeToDatabase();
will always be executed. But I want to avoid that because I do not need to write any stuff in to database in case of non whitelisted
domain.
任何想法?
推荐答案
我的想法是使用if来过滤app.post中的请求
例如,
My idea is to use if to filter the request inside the app.post so for example,
app.post('/products/:id', cors(corsOptions), function (req, res, next) {
if(req.header[origin]===whitelisted){
writeToDatabase();
res.json({ msg: 'This is CORS-enabled for a whitelisted domain.' }); }
});
这篇关于节点表达和路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!