node.js 创建一个接受参数的 expressjs 中间件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12737148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a expressjs middleware that accepts parameters
提问by Vartan Arabyan
I am trying to create a middleware that can accept parameters. How can this be done?
我正在尝试创建一个可以接受参数的中间件。如何才能做到这一点?
example
例子
app.get('/hasToBeAdmin', HasRole('Admin'), function(req,res){
})
HasRole = function(role, req, res, next){
if(role != user.role){
res.redirect('/NotInRole);
}
next();
}
回答by Jonathan Ong
function HasRole(role) {
return function(req, res, next) {
if (role !== req.user.role) res.redirect(...);
else next();
}
}
I also want to make sure that I don't make multiple copies of the same function:
我还想确保我不会制作同一功能的多个副本:
function HasRole(role) {
return HasRole[role] || (HasRole[role] = function(req, res, next) {
if (role !== req.user.role) res.redirect(...);
else next();
})
}
回答by chovy
app.get('/hasToBeAdmin', (req, res, next) => {
hasRole(req, res, next, 'admin');
}, (req,res) => {
// regular route
});
const hasRole = (req, res, next, role) => {
if(role != user.role){
res.redirect('/NotInRole');
}
next();
};
回答by zevero
Alternatively if you do not have too many cases or if role is NOT a string:
或者,如果您没有太多案例或角色不是字符串:
function HasRole(role) {
return function(req, res, next) {
if (role !== req.user.role) res.redirect(...);
else next();
})
}
var middlware_hasRoleAdmin = HasRole('admin'); //define router only once
app.get('/hasToBeAdmin', middlware_hasRoleAdmin, function(req,res){
})
回答by asdf
If you have various permissions levels you could structure them like this:
如果您有不同的权限级别,您可以像这样构建它们:
const LEVELS = Object.freeze({
basic: 1,
pro: 2,
admin: 3
});
/**
* Check if user has the required permission level
*/
module.exports = (role) => {
return (req, res, next) => {
if (LEVELS[req.user.role] < LEVELS[role]) return res.status(401).end();
return next();
}
}

