【问题标题】:Unable to modified/appened REQUEST in middleware无法在中间件中修改/附加请求
【发布时间】:2020-01-31 06:30:48
【问题描述】:

我是 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】:

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

    ??‍? 确保在if/else 条件中添加您的next()。所以,你可以复制下面的代码?并使用它:

    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?

    希望对你有帮助?。

    【讨论】:

    • 谢谢你,@Titus Sutio Fanpula,它对我有用,我已经使完整的中间件异步
    猜你喜欢
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    • 2015-09-11
    • 1970-01-01
    • 2017-12-15
    • 1970-01-01
    • 2011-03-06
    相关资源
    最近更新 更多