问题描述
路由器和控制器代码如下: 尝试使用 jwt 解码器,它提供对象:{_id,iat,exp} 但在邮递员中它返回空对象
===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 模式编写的签名令牌
const sendCustomerToken = (customer,statusCode,res) => { const token = customer.getSignedToken(); res.status(statusCode).json({ success: true,token }); };
基本上,它返回一个promise,如果你不等待它,它会返回一个null或空对象,因为它是过程性的
但是,如果您等待它,它会等待字符串可用的时间,然后像这样返回它
const sendCustomerToken = async (customer,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,}); };
您可能想要检查代码中可能查询数据库的承诺。
此外,如果解码不起作用,请尝试使用 jwt sign 方法 接收有效载荷、秘密和选项 - 有效载荷是受保护的数据您想返回,secret 是您可以使用加密生成的普通字符串,而 option 只是您令牌的生命周期。像这样
function() {
return jwt.sign({ id: this._id },});};`
像这样的环境变量
端口=5000 JWT_SECRET=4de5b205fa171927adb1444c06bd990fadd45ffe7a1309def8b5a JWT_EXPIRE=10min