首页 > 解决方案 > JWT 解码返回“[object Object]”

问题描述

我正在尝试解码发送到我的其余 API 服务器的 JSON Web 令牌。但是,当我尝试使用在网络令牌中发送的 _id 属性时,我无法让它工作。这是我正在使用的代码:

  jwt.verify(token, process.env.TOKEN_SECRET, { complete: true }, async (err, decoded) => {
    console.log(decoded)
    if (err) {
      res.status(400).json({
        error: 'Token is not valid'
      });
      return
    } else {

      // Verify user exists
      const userExists = await User.findById(decoded._id);
      if (userExists == [] || !userExists){
        res.status(400).json({
          error: 'Token is not valid'
        });
        return
      } else {
        req.decoded = decoded;
        next();
      }
    }
  });


这是我得到的控制台日志:[object Object]
这是记录的错误:(node:4) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '_id' of null 我将不胜感激!

标签: javascriptnode.jsexpressjwt

解决方案


而不是像这样记录信息: console.log(decoded)

你应该这样做:console.log(JSON.stringify(decoded))

您应该在控制台中很好地格式化您的对象。


推荐阅读