PassportJs 刷新会话变量?

PassportJs Refreshing Session Variables?

我正在使用带有节点的 PassportJS 来处理身份验证。 如果身份验证失败,我希望暂时保存输入,以便我可以在网页上重新加载它们并显示某种错误消息:

护照登录攻略:

const localLogin = new LocalStrategy(
    {
        passReqToCallback: true,
        usernameField: 'email',
        passwordField: 'password'
    },
    async (req, email, password, done) => {
        try {
            const user = await User.findOneByEmail(email);
            if (user) {
                const passwordsMatch = await PasswordHash.compare(password, user.password);
                if (passwordsMatch) {
                    return done(null, user);
                }
            }

            console.log('Sending inputs back to the user : ' + req.sessionID);
            req.session.inputs = {
                email: email,
                . . . 
            }
            return done(null, false);

        } catch (err) {
            console.log(err);
            return done(err);
        }
    });

帐户登录路由器:URL Express 中的结构('/accounts/*'):

accountsRouter.get('/login', async (req, res) => {
    res.render('accounts/login.ejs', 
    { 
        inputs: req.session.inputs
    });

    console.log("BEFORE DELETE: " + req.session.inputs);
    delete req.session.inputs;
    console.log("AFTER DELETE: " + req.session.inputs);
});

我希望它能存储输入并在登录失败后将它们显示给用户。如果用户点击刷新 Chrome (GET /accounts/login) 而不是再次点击登录按钮 (POST /accounts/login),req.session.inputs 变量应该为空.但是,出于某种原因,即使控制台显示该变量已被删除,该变量在刷新浏览器时仍保持其值。

这是我得到的输出:

# Getting the login page (blank fields)
BEFORE DELETE: undefined
AFTER DELETE:  undefined
GET /accounts/login 200 7.042 ms - 2327

# Click the login button
Sending inputs back to the user : Km2o9VFTWkvQxsz28Tt7Tx9mzL2NS14f
POST /accounts/login 302 31.850 ms - 74

# Login fails, displaying inputs back to user. Delete variable on render
BEFORE DELETE: [object Object]
AFTER DELETE: undefined
GET /accounts/login 200 3.919 ms - 2338

# Hits Chrome refresh on login page, req.session.inputs should be undefined here but it's not?
BEFORE DELETE: [object Object]
AFTER DELETE: undefined
GET /accounts/login 200 2.404 ms - 2338

如果有人能指出正确的方向,我将不胜感激!

我怀疑浏览器正在缓存输入值。

当您渲染视图时,明确设置您的输入值,如下所示:

<input type="text" name="textfield" value="">

确定它不仅在 Passport 中,而且在 Express Session 中也普遍存在。发现必须调用 await req.session.save(); 否则任何更改仅在本地进行,不会保存在会话存储中。