简体   繁体   English

nodejs module.exports 返回未定义的 JSON web 令牌

[英]nodejs module.exports returns undefined for JSON web token

I am having some issue while getting console.log of my decoded token.我在获取解码令牌的 console.log 时遇到了一些问题。 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 nodejs module.exports 返回未定义的 JSON web 令牌

Yes, your module.exports function has no return value so the return value will naturally be undefined .是的,你的module.exports function 没有返回值,所以返回值自然是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 .您从令牌中获得的数据是 nn req.userData然后您调用next()继续路由到其他请求处理程序,以便其他请求处理程序应该访问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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM