简体   繁体   中英

nodejs module.exports returns undefined for JSON web token

I am having some issue while getting console.log of my decoded token. It gives me undefined.

const jwt = require("jsonwebtoken");

module.exports = (req, res, next) => {
  try {
    const token = req.headers.authorization.split(" ")[1];
    const decodedToken = jwt.verify(token, "secret_this_should_be_longer");
    let details = (req.userData = {
      email: decodedToken.email,
      userId: decodedToken.userId,
    });
    console.log(details.email, details.userId);
    next();
  } catch (err) {
    res.status(401).json({ message: "Auth failed!" });
  }
};

nodejs module.exports returns undefined for JSON web token

Yes, your module.exports function has no return value so the return value will naturally be undefined . That is expected.

The data you've gotten from the token is nn req.userData and then you call next() to continue routing to other request handlers so those other request handlers should be access the decoded token data on req.userData .


FYI, this code is easy to misread:

let details = (req.userData = {
  email: decodedToken.email,
  userId: decodedToken.userId,
});
console.log(details.email, details.userId);

I now understand what it does, but did not the first few times I glanced over it. It would be much clearer like this:

req.userData = {
  email: decodedToken.email,
  userId: decodedToken.userId,
};
console.log(req.userData);

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