Express-session Req.user Is Undefined
I'm trying to use express session to login users. I'd like users to be able to go to a profile page and view their user data if they have logged in. I've been stuck here for days.
Solution 1:
You should define isLoginedIn funtion in routes.js as follow:
// route middleware to ensure user is logged in
function isLoggedIn(req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/');
}
Then replace:
app.route('/profile')
.get(function(req, res){
console.log('req.user', req.user)
if(!req.user){
res.render('profile', {user: "You're not logged in"})
}
if(req.user){
res.render('profile', {user: req.user})
}
})
by:
// PROFILE SECTION =========================
app.get('/profile', isLoggedIn, function(req, res) {
res.render('profile.ejs', {
user : req.user
});
});
Post a Comment for "Express-session Req.user Is Undefined"