Home > Net >  (Express)How to pass a value from function to another one in express.Router().get
(Express)How to pass a value from function to another one in express.Router().get

Time:01-24

How I can pass value from function to another one at router.get

router.get('/someurl', (req, res, next) => {
const token = req.headers.authorization.split(' ')[1] //jwtToken
const jwt = jwt.verify(
    token,
    jwtSecret
)
...do something to pass value to the next function
}, )

CodePudding user response:

You can use res.locals to do that

An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any).

So in your case

router.get(
  "/someurl",
  (req, res, next) => {
    const token = req.headers.authorization.split(" ")[1]; //jwtToken
    const jwt = jwt.verify(token, jwtSecret);
    // pass to res.locals so I can get it in next() middleware
    res.locals.token = token;
    next();
  },
  (req, res, next) => {
    // inside the next() middleware
    // get token from res.locals
    const previousToken = res.locals.token;
  }
);

  •  Tags:  
  • Related