【问题标题】:Property '_id' does not exist on type 'string | JwtPayload'. Property '_id' does not exist on type 'string'类型“字符串”上不存在属性“_id”| JwtPayload”。 “字符串”类型上不存在属性“_id”
【发布时间】:2021-11-27 10:52:22
【问题描述】:

正如您在 NodeJS 代码中看到的那样,我正在从 URL 中提供的 Postman 令牌中获取用户,但我正在努力从给定的令牌号中取回 _id 属性。我想要的是解码后的 id._id 以便我可以在进一步的操作中使用该 id

const jwt = require('jsonwebtoken')
const User = require('../model/users')
const auth = async (req, res, next) => {
    try {
          const token = req.header('Authorization').replace('Bearer', '')
          const decoded = jwt.verify(token, 'thisisfromabhishek')

`the property _id does not exist on decoded`
          const user = await User.findOne({ _id: decoded._id, 'tokens.token': token })

        if (!user) {
            throw new Error()
        }
        req.token = token
        req.user = user
        next()
       } catch (e) {
        res.status(401).send({ error: 'Please authenticate.' })
    }
}

module.exports = auth

【问题讨论】:

  • 你能记录解码变量吗?
  • 它没有在控制台中显示任何错误,只是没有从编辑器中获取一些自动完成的 _id 属性,但因此我无法获取 _id
  • 你能出示你的令牌吗?
  • “标记”:[{ “标记”: “eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MTVlZWY1MmM4NTZlYmFkMTM3NTIzNjIiLCJpYXQiOjE2MzM2MTE2MDJ9.13oo0gCXb_fGyElG4g3Uakf2g7LGdih6fV5pHOK6vkI”, “_id”:的ObjectId( “615eef52c856ebad13752364”)}] 跨度>
  • 因此您的令牌存储在 JSON 中。您传递给jwt.verify(token... 的token 的确切值是多少?它应该只是令牌本身,eyJhb.....

标签: javascript node.js mongodb jwt


【解决方案1】:

Typescript 不知道令牌中的 _id。 数据声明应该会有所帮助。

interface JwtPayload {
  _id: string
}

const { _id } = jwt.verify(token, 'thisisfromabhishek') as JwtPayload

req.user = await User.findOne({ _id, 'tokens.token': token })

【讨论】:

    【解决方案2】:

    在 Bearer 之后你没有给空间。

    const token = req.header('Authorization').replace('Bearer', '') //here is the problem place space after Bearer
              const decoded = jwt.verify(token, 'thisisfromabhishek')

    【讨论】:

      猜你喜欢
      • 2021-01-11
      • 2019-08-25
      • 2020-12-16
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-27
      • 1970-01-01
      相关资源
      最近更新 更多