路由器和 Controller 代码如下: 尝试使用 jwt 解码器,它提供对象:{_id,iat,exp} 但在 postman 中它返回空对象
===router===
router.get("/secret", requireSignin, (req, res) => {
res.json({
user: req.user,
});
});
===controller===
exports.requireSignin = expressJwt({
secret: process.env.JWT_SECRET,
algorithms: ["HS256"],
userProperty: "auth",
});```
最佳答案
对我来说,这发生在我没有异步等待一个函数时,该函数将返回我针对 MongoDB 模式编写的签名 token ,就像这样
const sendCustomerToken = (customer, statusCode, res) => { const token = customer.getSignedToken(); res.status(statusCode).json({ success: true, token }); };
基本上,它返回一个 promise ,如果你不等待它,它会返回一个 null 或空对象,因为它是过程性的
但是如果你等待它,它会等待字符串可用的时间然后像这样返回它
const sendCustomerToken = async (customer, statusCode, res) => { const token = await customer.getSignedToken(); res.status(statusCode).json({ success: true, token }); };
模式方法
customerAuthSchema.methods.getSignedToken = async function() { return jwt.sign({ id: this._id }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRE, }); };
您可能希望在查询数据库的代码中检查 promise 。
另外,如果解码不起作用,请尝试使用 jwt sign method 接收有效载荷、 secret 和选项 - 有效载荷是 protected 数据你想返回,secret 是你可以使用 crypto 生成的普通字符串,option 只是你的 token 的生命周期。像这样
function() {
return jwt.sign({ id: this._id }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRE, });};`
像这样的环境变量
PORT=5000 JWT_SECRET=4de5b205fa171927adb1444c06bd990fadd45ffe7a1309def8b5a JWT_EXPIRE=10min
关于node.js - 具有 jwt 授权的 get 方法返回空对象,我们是否需要解码 jwt token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66929705/