Node.js 具有jwt授权的get方法返回空对象,我们需要解码jwt令牌吗?
路由器和控制器代码如下所示: 尝试使用jwt解码器,它提供对象:{u id,iat,exp},但在postman中它返回空对象Node.js 具有jwt授权的get方法返回空对象,我们需要解码jwt令牌吗?,node.js,express,jwt,token,decode,Node.js,Express,Jwt,Token,Decode,路由器和控制器代码如下所示: 尝试使用jwt解码器,它提供对象:{u id,iat,exp},但在postman中它返回空对象 ===router=== router.get("/secret", requireSignin, (req, res) => { res.json({ user: req.user, }); }); ===controller=== exports.requireSignin = expressJw
===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});}代码>
基本上,它返回一个承诺,如果您不等待它,它将返回一个null或空对象,因为它是过程性的
但是,如果您等待它,它会等待字符串可用的时间,然后像这样返回它
const-sendCustomerToken=async(customer,statusCode,res)=>{const-token=wait-customer.getSignedToken();res.status(statusCode).json({success:true,token});}代码>
模式方法
customerAuthSchema.methods.getSignedToken=async function(){return jwt.sign({id:this.\u id},process.env.jwt\u SECRET,{expiresIn:process.env.jwt\u EXPIRE,})代码>
您可能希望在查询数据库的代码中检查承诺
此外,如果解码不起作用,请尝试使用jwt符号方法,该方法接收有效载荷、密码和选项-有效载荷是您要返回的受保护数据,密码是您可以使用加密生成的普通字符串,而选项只是您令牌的使用寿命。像这样
function() {
return jwt.sign({ id: this._id }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRE, });};`
使用像这样的环境变量
端口=5000
JWT_SECRET=4de5b205fa171927adb1444c06bd990fadd45ffe7a1309def8b5a JWT_EXPIRE=10分钟
在《邮递员》杂志上,你传递过代币了吗?