Sur*_*off 7 javascript routes node.js express
// state edit route
app.get("/map/:symbol/edit", isLoggedIn, function(req, res){
State.findOne({symbol: req.params.symbol}, function(err, state){
if(err){
console.log(err);
} else
{
res.render("edit", {state: state});
}
});
});
Run Code Online (Sandbox Code Playgroud)
在上面的代码片段中,isLoggedIn是检查身份验证的中间件函数。其定义如下:
// middleware function
function isLoggedIn(req, res, next){
if(req.isAuthenticated()){
return next();
}
res.redirect("/admin");
}
Run Code Online (Sandbox Code Playgroud)
那么,问题是,如何将字符串、整数或路径变量等参数传递给中间件函数,以便可以在路由 url 中使用?
Har*_*val 19
我有同样的要求,这种方法对我有用。
中间件文件 validate.js
exports.grantAccess = function(action, resource){
return async (req, res, next) => {
try {
const permission = roles.can(req.user.role)[action](resource);
// Do something
next();
}
catch (error) {
next(error)
}
}
}
Run Code Online (Sandbox Code Playgroud)
在路由文件中使用中间件。grantAccess('readAny', 'user')
router.get("/",grantAccess('readAny', 'user'), async (req,res)=>{
// Do something
});
Run Code Online (Sandbox Code Playgroud)