【问题标题】:I cant get the user id that is in the payload from my middleware in my get request我无法在我的获取请求中从我的中间件获取有效负载中的用户 ID
【发布时间】:2021-04-09 12:23:14
【问题描述】:

您好,我将 jwt 与 node 和 express 和 mongoose 一起使用,我创建了一个可以在这里工作的注册 API 是代码 jwt.sign({ payload, }, process.env.jwtSecret, { expiresIn: '999h' }, (err, token) => { console.log(token) });

这是有效的,但我有一个身份验证中间件,我从标头中的 x-auth-token 获取令牌我认为这是有效的,但我不确定这里是代码:

module.exports = function (req, res, next) {

    //get the token 
    const token = req.header("x-auth-token");

    //check if not token 
    if (!token) {
        return res.status(401).json({ msg: "No token, authorization denied" });
    }

    //verify token 
    try {
        const decoded = jwt.verify(token, "jwttokensecret22030293020003023");

        req.user = decoded.user;
        next()

    } catch (err) {
        res.status(401).json({ msg: "Token is not valid" })
    }


}

现在我想让用户访问受保护的路由,受保护的路由的工作方式就像如果我从标头中删除令牌,我无法获取令牌,但我想从 req.user 获取用户 ID,但我不能我得到未定义这里是代码:

router.get('/testauth', auth, async (req, res) => {
    try {
        const user = await User.findById(req.user.id)

        res.json(req.user)
    } catch (error) {
        console.log(error.message)
        res.status(500).send("Server error")
    }
})

【问题讨论】:

    标签: node.js express jwt jwt-auth


    【解决方案1】:

    解决了我有变量 req.user = decoded.user 而不是 decoded.payload.id 谢谢

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-14
      • 2013-01-09
      • 2011-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多