每个请求都表示更改会话 [英] Express change session every request
问题描述
我有一个登录功能
app.post('/doLogin', function(req,res){
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();
} else {
req.session.user_role = "null";
console.log("Wrong login");
}
}
res.send({redirect: "/"});
});
});
该函数用于将变量保存到会话中 req.session.user_role = "user";
但是当新的请求检查用户是否登录时
This function is used to save a variable into session req.session.user_role = "user";
But when the new request to check user logged in or not
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");
}
});
然后返回始终是已注销",因为会话已更改.我使用Redis存储会话,我认为是Redis的故障,因为当我停止使用Redis时,就可以了请帮帮我!
Then return always is "Logged out", because the session is changed. I use Redis to store session, I think it is Redis fault because when I stop using Redis, it's OK Please help me!
推荐答案
做事最好的方式是始终让 Express 处理它,如果可以的话.
The best way to do things is to always let Express deal with it, if it can.
https://flaviocopes.com/express-sessions/(更新会话教程虽然链接不应被视为答案)
https://flaviocopes.com/express-sessions/ ( Updated Session tutorial although links should not be considered answers )
有一个链接可以向您展示如何在 Express 中为会话设置 redis.在处理会话时,您甚至不必自己查询 redis,这是 node 中的中间件的工作.
There's a link that can show you how to set up redis for sessions in Express. You shouldn't have to even query redis yourself when dealing with sessions, that's a job for middleware in node.
这篇关于每个请求都表示更改会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!