首页 > 解决方案 > 无法使用快速会话将用户信息传递到不同的路线?

问题描述

所以我的登录帖子路由验证了用户并从数据库中获取用户信息。然后我想将其发送到重定向路线。我正在使用会话,但有关如何操作的教程和以前的问题要么不起作用,要么已被弃用。

这就是我正在做的获取我通过这一行保存在 req.session 中的用户信息

req.session = Users

然后我输入这个来验证我得到了用户信息

console.log(req.session)

它有效,我在服务器终端中看到了所有信息。

但是,一旦我尝试在重定向路由中传递信息,我就无法检索会话。

所以这是路由器端代码

router.post('/Login', async (req,res)=> {
  
 try {
    
const Users = await User.findOne({ email:req.body.email}).exec()
const auth = await bcrypt.compare(req.body.password, Users.password)

    if (auth){
  
req.session = Users;
res.redirect('./profile' )  

}  
  
 else { res.send('invalid credentials')}
       
    }
      catch (err) { 
       
        console.log('error',err)
        res.status(500).send('invalid credentials')
    }

})

// Profile page
router.get(('/profile'), (req, res)=>

res.render('Projects/file.ejs', {info:req.session}

))


文件.ejs

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
  <h3>User info</h3>
  <p><%= info %></p>

</body>
</html>

错误信息

error TypeError: req.session.touch is not a function
    at ServerResponse.end (C:\Users\Moe\Desktop\Login Practice\node_modules\express-session\index.js:330:21)
    at ServerResponse.redirect (C:\Users\Moe\Desktop\Login Practice\node_modules\express\lib\response.js:951:10)
    at C:\Users\Moe\Desktop\Login Practice\routes\api\projects.js:46:6

第 46 行是

res.redirect('/profile)

有谁知道如何解决这一问题?

标签: node.jsexpresssession

解决方案


您正在使用 覆盖请求对象上的整个会话属性req.session = Users。相反,使用req.session.user = Users

使用时重命名Users为. 返回单个对象。useruser.findOnefindOne


推荐阅读