kashif
kashif

Reputation: 193

Unable to modified/appened REQUEST in middleware

I am new to nodejs and typescript and I want to add a new parameter in req.body say req.body.jwt_token.

I am using a middleware to update the request data model. The issue is that i am able to access (console.log works) the new key req.body.jwt_token just work in that function and is not accessible(don't even exist) apart from that.

I want to use req.body.jwt_token in some controller.

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

Please suggest the solution for this problem. how can i achieve this in nodejs and typescript. I am using express as framework

Thank You

Upvotes: 0

Views: 124

Answers (1)

Titus Sutio Fanpula
Titus Sutio Fanpula

Reputation: 3613

💡 The only reason why you can not access req.body.jwt_token in your controller is that before you set the value, you next().

👨🏽‍🏫 Make sure to add your next() inside if/else condition. So, you can copy this code below 👇 and use it:

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

Maybe this answer will help you to know the reason: passing value from middleware to controller in restify using req.data is not working?

I hope it can help you 🙏.

Upvotes: 1

Related Questions