创build一个接受参数的expressjs中间件

我正在尝试创build一个可以接受参数的中间件。 如何才能做到这一点?

app.get('/hasToBeAdmin', HasRole('Admin'), function(req,res){ }) HasRole = function(role, req, res, next){ if(role != user.role){ res.redirect('/NotInRole); } next(); } 

       

网上收集的解决方案 "创build一个接受参数的expressjs中间件"

 function HasRole(role) { return function(req, res, next) { if (role !== req.user.role) res.redirect(...); else next(); } } 

我也想确保我不会做同一个函数的多个副本:

 function HasRole(role) { return HasRole[role] || (HasRole[role] = function(req, res, next) { if (role !== req.user.role) res.redirect(...); else next(); }) } 

或者,如果您没有太多情况,或者angular色不是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){ }) 

如果你有不同的权限级别,你可以像这样构造它们:

 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(); } } 
 app.get('/hasToBeAdmin', function(req, res, next){ hasRole(req, res, next, 'admin'); }, function(req,res){ // regular route }); var hasRole = function(req, res, next, role){ if(role != user.role){ res.redirect('/NotInRole'); } next(); };