javascript - 如何将参数传递给 Express JS 中的中间件函数?
问题描述
// 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});
}
});
});
在上面的代码片段中,isLoggedIn是检查身份验证的中间件函数。其定义如下:
// middleware function
function isLoggedIn(req, res, next){
if(req.isAuthenticated()){
return next();
}
res.redirect("/admin");
}
所以,问题是,如何将字符串、整数或路径变量等参数传递给中间件函数,以便在路由 url 中使用?
解决方案
我有同样的要求,这种方法对我有用。
中间件文件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)
}
}
}
在路由文件中使用中间件。grantAccess('readAny', 'user')
router.get("/",grantAccess('readAny', 'user'), async (req,res)=>{
// Do something
});
推荐阅读
- javascript - 引导程序如何确定复选框/单选按钮的选中状态
- .net - ag-grid 是否支持 .netcore 上的服务器端过滤
- python - 使用 Python Pandas 将嵌套的 json 解析为 csv
- javascript - http resquest中的多个数据包
- python - 熊猫在将值设置为数据框时更改日期时间
- kubernetes - Janusgraph 部署在 kuberntes 上,存储为 Cassandra 给出错误:无法实例化配置的图
- linux - ';'的计数 在列
- oracle - Oracle 将结果集放入 FORALL 中的变量中
- c# - 没有详细信息的 Elasticsearch serilog 错误
- flutter-web - 使用 Flutter 在 Web 浏览器中获取位置?