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
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:
Your session middleware is not getting properly run.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With