无法在 express 中存储和管理会话

Unable to store and manage session in express

我不熟悉 express 并使用 express-session 在我的应用程序中管理登录。 我关注了一个博客并声明我的会话如下:-

app.use(session({
secret:'Keep It Secret',
name : 'uniqueSessionID',
resave : true,
saveUninitialized : true,
cookie : { secure : false, maxAge : 3600000, loggedIn : false, username : "" }
}));

问题是在成功登录后我正在更新会话并打印它,输出到:-

    Session {
  cookie: {
    path: '/',
    _expires: 2021-12-27T13:16:17.355Z,
    originalMaxAge: 3600000,
    httpOnly: true,
    secure: false,
    loggedIn: true,
    username: 'pushkar@gmail.com'
  }
}

但是在那之后,当我验证路由时,会话保持不变,如下所示:-

    Session {
  cookie: {
    path: '/',
    _expires: 2021-12-27T13:16:17.355Z,
    originalMaxAge: 3600000,
    httpOnly: true,
    secure: false
  }
}

我都试过了,需要帮助。

这是我登录并创建会话的登录名:-

const login = (req, res, next) => {
console.log(req.body);
const email = req.body.email;
const password = req.body.password;

if(email == "" && password == ""){
    req.flash("message","please fill in the required fields");
    res.redirect("/admin/login");
}
else if(email == ""){
    req.flash("message", "please fill in the email");
    res.redirect("/admin/login");
}
else if(password == ""){
    req.flash("message", "please fill in the password");
    res.redirect("/admin/login");
}
else {
    user.findOne({email : email}, function(err, data){
        debugger;
        if(err){
            req.flash("message", "Username not found");
            res.redirect("/admin/login");
        }
        else {
            if(data.password == password){
                req.session.cookie.loggedIn = true;
                req.session.cookie.username = email;
                req.session.save(function(err) {
                    if (err) console.log(err);
                })
                console.log(req.session);
            }
            else{
                req.flash("message", "Invalid Password");
                res.redirect("/admin/login");
            }
            res.redirect("/admin/dashboard");
        }
    })
}

};

这是我的身份验证功能:-

exports.authenticated = (req, res, next) => {
debugger;
console.log(req.session);
if(req.session.cookie.loggedIn) {
    next();
}
else {
    res.redirect("/admin/login");
}
}

设置值不正确,你想保存到 req.session.cookie 你设置 uniqueSessionID cookie 选项的地方,而不是保存的值。

this tutorial for example

尝试

//to write
req.session.loggedIn = true;
req.session.username = email;

//to read
if(req.session.loggedIn) {
    next();
}

如果一切正常,也许您希望在重新启动之间使会话永久化,所以请看下一步 Example with permanent storage