【问题标题】:JWT TypeError: Cannot read properties of undefined (reading 'jwt')JWT 类型错误:无法读取未定义的属性(读取 \'jwt\')
【发布时间】:2022-12-17 12:31:55
【问题描述】:

我正在创建一个 JWT 令牌,但出现了这个错误。 而且我收到此错误:TypeError:无法读取未定义的属性(读取'jwt') 这是代码:

const maxAge = 3*24*60*60;  
    db.query('SELECT * FROM USERS WHERE EMAIL=?', [email], async (err, results, fields)=>{
        if(err){
            console.log(err);
        }       
        else if(results.length > 0)
        {
            const comparison = await bcrypt.compare(password, results[0].password); 
            if(comparison){
                 

                const token = jwt.sign({user_id:results[0].user_id, name:results[0].name},
                    process.env.SECRET_KEY , { expiresIn:maxAge });
                res.cookie('jwt', token, { httpOnly:true, maxAge:maxAge*1000 });
                console.log(token);
                return res.render('user', {
                    message: results[0].name
                });
            }
            else{
                res.render('login', {
                    message: 'Incorrect Email and Password.'
                });
            }
        }
        else{
            res.render('login', {
                message: "Email doesn't Exists."
            });
        }
    })

这是中间件功能的代码

const requireAuth = (req, res, next)=>{
    const token = res.cookies.jwt;    //  Here this error came up    
    if(token){
        jwt.verify(token, process.env.SECRET_KEY, (err, decoded)=>{
            if(err){
                console.log(' You are not logged in.');
                res.redirect("/");
            }
            else{
                console.log(decoded);
                next();
            }
        });
    }   
    else{
        res.redirect('/');
    }
}

【问题讨论】:

  • 你能在这里粘贴你的依赖关系,你的require/import吗?您的服务器依赖项名称是什么?它将帮助我理解这里使用的 JWT 依赖项。

标签: node.js authentication jwt


【解决方案1】:

你的代码在那里是错误的:

const token = res.cookies.jwt;

您应该从请求中读取 cookie。

我不知道语法,这取决于此处用于服务器的依赖项。你能告诉我们服务器依赖性吗?

【讨论】:

    【解决方案2】:

    修正中间件代码后

    const token = res.cookies.jwt
                to 
    const token = req.cookies.jwt
    

    代码开始工作了吗?

    【讨论】:

      猜你喜欢
      • 2020-08-19
      • 2020-06-26
      • 2018-04-29
      • 2022-12-08
      • 2022-12-01
      • 2022-12-21
      • 2022-12-24
      • 2022-12-25
      • 2023-01-21
      相关资源
      最近更新 更多