Home > Software engineering >  Unable to pass user information to different route using express sessions?
Unable to pass user information to different route using express sessions?

Time:10-08

So my login post route validates the user and obtains User info from the data base. I would like to then send that off to the re-direct route. I am using sessions but the tutorials and previous questions on how to do it either don't work or are deprecated.

This is what I am doing to obtain user info I save in req.session by this line

req.session = Users

I then type this to verify I got the user info

console.log(req.session)

It works and I see all the information in the server terminal.

However, as soon as I try to pass the information in the redirect route, I cannot retrieve sessions.

So here is the router side code

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}

))


file.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 message

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

line 46 is

res.redirect('/profile)

Does anyone know how to fix this?

CodePudding user response:

You're overwriting the entire session property on the request object with req.session = Users. Instead, use req.session.user = Users

Rename Users to user when using user.findOne. findOne returns a single object.

  • Related