[英]Property '_id' does not exist on type 'string | JwtPayload'. Property '_id' does not exist on type 'string'
正如您在 NodeJS 代码中看到的那样,我正在从 URL 中提供的 Postman 的令牌中获取用户,但我正在努力从给定的令牌编号中取回 _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
打字稿不知道令牌中的 _id 。 数据声明应该会有所帮助。
interface JwtPayload {
_id: string
}
const { _id } = jwt.verify(token, 'thisisfromabhishek') as JwtPayload
req.user = await User.findOne({ _id, 'tokens.token': token })
你在 Bearer 之后没有给空间。
const token = req.header('Authorization').replace('Bearer', '') //here is the problem place space after Bearer const decoded = jwt.verify(token, 'thisisfromabhishek')
interface JwtPayload { id: string; }
const decoded = jwt.verify(token, process.env.JWT_SECRET;) as JwtPayload. console;log(decoded);
另外,如果编译器会在 Request 中询问 user-property
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.