简体   繁体   中英

How do I create a json object that gets appended to the actual response in node.js

I use jSON web tokens (simple-jwt) with my node application. I have a middleware(using express.js) that checks whether the token isValid?() and returns the user data if true.

But when the user does a GET request to localhost:8080/home or any other route, I need it to return the user data(from the tokenValidation middleware) and also the actual contents of localhost:8080/home. I can't use response.json({}) twice since that would be considered as two responses.

What is the standard way to append the user data with the actual json response?

If the code is required, let me know.

In your middleware you can add a new property to the req object.

(req, res, next) => {
  const user = ...queryUser
  req.user = user;
  next();
}

And in your route handler :

(req, res) => {
  const user = req.user;
  const otherData = { data : 'junk' };
  res.status(200).send({ user, otherData });
}

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