无法在中间件中修改/添加请求

问题描述 投票:0回答:1

我是nodejs和Typescript的新手,我想在req.body中添加一个新参数,例如req.body.jwt_token

我正在使用中间件更新请求数据模型。 问题是我能够访问(console.log运行)新密钥req.body.jwt_token仅在该功能中起作用,除此之外不能访问(甚至不存在)。

我想在某些控制器中使用req.body.jwt_token

export function httpsProtocol(req: Request, res: Response, next: NextFunction) {
    try {
        if (req.headers.authorization != undefined) {
            let authorization = req.headers.authorization;
            let authorizationArr: string[] = authorization.split('Bearer')
            if (authorizationArr[1] != undefined) {
                let jwtToken = "Bearer " + authorizationArr[1].trim();
                req.headers.Authorization = jwtToken;
                req.body.jwt_token = authorizationArr[1].trim();
                console.log(req.body.jwt_token); //able to console this
            }

        }
    } catch (error) {
        return res.status(422).json({
            message: "something goes wrong",
            error: error
        });
    }
    next();
};

请提出解决方案的建议此问题。我如何在nodejs和typescript中实现这一点。我正在使用express作为框架

谢谢

javascript jquery node.js typescript express
1个回答
1
投票

💡您无法在控制器中访问req.body.jwt_token的唯一原因是在设置该值之前,您需要next()

👨🏽‍🏫确保在next()条件内添加if/else。因此,您可以复制 below下面的代码并使用它:

export function httpsProtocol(req: Request, res: Response, next: NextFunction) {
  try {
      if (req.headers.authorization != undefined) {
          let authorization = req.headers.authorization;
          let authorizationArr: string[] = authorization.split('Bearer')
          if (authorizationArr[1] != undefined) {
              let jwtToken = "Bearer " + authorizationArr[1].trim();
              req.headers.Authorization = jwtToken;
              req.body.jwt_token = authorizationArr[1].trim();
              console.log(req.body.jwt_token); //able to console this
              // your next here
              next();
          } else {
            next(); // next or do some stuff
          }
      } else {
          next(); // next or do some stuff
      }
  } catch (error) {
      return res.status(422).json({
          message: "something goes wrong",
          error: error
      });
  }
  // next(); your next here only make your req.body.jwt_token is undefined
};

也许此答案将帮助您了解原因:passing value from middleware to controller in restify using req.data is not working?

希望它能对您有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.