Creating a expressjs middleware that accepts parameters

前端 未结 5 2115
自闭症患者
自闭症患者 2020-12-07 10:28

I am trying to create a middleware that can accept parameters. How can this be done?

example

app.get(\'/hasToBeAdmin\', HasRole(\'Admin\'), function(         


        
5条回答
  •  旧时难觅i
    2020-12-07 11:19

    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) {
    
    })
    

提交回复
热议问题