简体   繁体   中英

How to pass a parameter to middleware function in 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});
    }
  });
});

In the above code snippet, isLoggedIn is the middleware function to check for authentication. Its definition is given below:

// middleware function
function isLoggedIn(req, res, next){
  if(req.isAuthenticated()){
    return next();
  }
  res.redirect("/admin");
}

So, the question is, how to pass a parameter like a string, an integer or a path variable to the middleware function so that it can be used in the routing url ?

I had the same requirement and this approach works for me.

Middleware file 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)
        }
    }
}

Use of middleware in route file. grantAccess('readAny', 'user')

router.get("/",grantAccess('readAny', 'user'), async (req,res)=>{
    // Do something     
});

Follow this approach, it might do the job for you

app.use(function(req, res, next){
    console.log(req);
    this.req = req;
    // assign value like this
    this.req.body.custom_data = ['zz', 'aaa', ....];
    next();
});

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

function isLoggedIn(req, res, next){
   console.log(req.body);
   if(req.isAuthenticated()){
      return next();
   }
   res.redirect("/admin");
}

This is the way I'm using it, I take a little bit of Hardik Raval answer.

helpers.validateRole = (roles) => {
    return async (req, res, next) => {
        try {
            const authHeader = req.headers['authorization']
            const token = authHeader && authHeader.split(' ')[0]
            if (token == null) return res.json({error:true, msg: "Unauthorized"})
            const user = jwt.decode(token)
            let isValid = false
            roles.map((r,i)=>{
                if (r === user.role){
                    isValid = true
                }
            })
            if (isValid){
                // User role is valid
                next();
            }else{
                // User role is not valid
                util.returnError("Unauthorized", res);
            }
        }
        catch (error) {
            next(error)
        }
    }
}

And I called like this.

router.get(  "/requirements/list_of_requirements/:page/:rows",  isAuthenticated, validateRole([6]),  async (req, res) => {
//* All the logic
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM