正如您在 NodeJS 代码中看到的那样,我正在从 URL 中提供的 Postman token 中获取用户,但我正在努力从给定的 token 号中取回 _id 属性。我想要的是decoded._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
最佳答案
Typescript 不知道 token 中的 _id。
数据声明应该有所帮助。
interface JwtPayload {
_id: string
}
const { _id } = jwt.verify(token, 'thisisfromabhishek') as JwtPayload
req.user = await User.findOne({ _id, 'tokens.token': token })
关于javascript - 类型 '_id' 上不存在属性 'string | JwtPayload' 。类型 '_id' 上不存在属性 'string',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69479595/