首页 > 解决方案 > 如何将参数传递给 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 中使用?

标签: javascriptnode.jsexpressroutes

解决方案


我有同样的要求,这种方法对我有用。

中间件文件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     
});

推荐阅读