I have a function to login
app.post(\'/doLogin\', function(req,res){
db.users.findOne({username: req.body.username}, function(err, user) {
if
Maybe there are some asynchronous errors in your code. Every time you have the asynchronous operation(like a callback), you should make sure that your rest code is executed after the callback function, so you may put the code into the callback function. Just like this:
db.users.findOne({username: req.body.username}, function(err, user) {
if( err ) {
console.log("Login fail");
}
else if (user != null) {
if (req.body.password == user.password) {
req.session.user_role = "user";
req.session.save();
res.send({redirect: "/"});
} else {
req.session.user_role = "null";
console.log("Wrong login");
res.send({redirect: "/"});
}
}
});
And the app.get
should look like:
app.get('/', function(req,res){
redis.get('sess:' + req.session.id, function(err, result){
console.log("Get session: " + util.inspect(JSON.parse(result),{ showHidden: true, depth: null }));
if ((req.session.user_role == "user")) {
console.log("Logged in");
} else {
console.log("Logged out");
}
});
});