Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why assigning a session variable isn't working? Node.js

Im trying to build a simple login system but when i try the asign the session i get this error

Cannot set property 'user' of undefined

However this is my code:

app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,}))

This is the login controller:

    const loginModel = require('../model/loginModel');
    module.exports = {
    login : async function(req,res){
        try {
        const query = await loginModel.login(req.body.email,req.body.password);
        if(query != null){
            req.session.user = query;
            res.status(200).json(req.session.user);
        }else{
            res.status(401).json({error : true});
        }
        } catch (error) {
            console.error(error.message);
            res.status(500).send('something went wrong');
        }
        
    }
}

NOTE : login model is 100% working and its retrieving the user from database

like image 468
gary Avatar asked Apr 21 '26 14:04

gary


1 Answers

Well, something is not working properly with the session middleware because req.session does not appear to exist based on the error you are getting. Here are some of the things it could be:

  1. Your session middleware is not getting properly run.

  2. Your session middleware is running AFTER the route in which you're trying to use req.session. It must be run BEFORE because that middleware is what creates the req.session object and loads its data based on the session cookie.

  3. Based on this code, you could also get this error if you were passing the wrong req argument to your login(req, res) method so it's worth checking that too.

We can't see specifically what the problem is without seeing more code.

like image 97
jfriend00 Avatar answered Apr 24 '26 03:04

jfriend00