注销和重新登录时会话变量设置不一致

问题描述 投票:0回答:0

我的会话变量设置不一致有问题。这是我的会议声明。

app.use(
    session({
        secret: process.env.MYSTERY,
        resave: false,
        saveUninitialized: false,
        store: store,
        cookie: {
            maxAge : 86400000, // expires in 1 day (in milliseconds)
            httpOnly : true,
            sameSite : "strict"
        }
    })
)

然后,当用户成功登录时,我将“isAuth”和“用户名”存储到会话中。以下是我登录的帖子路线。

exports.loginCustomer = async (req, res) => {
    try {
        await check('username')
            .custom(async (value) => {
            const customer = await Customer.findOne({ username : value })
            if (!customer) {
                throw new Error('The username or password you entered does not match any account')
            }
            const password = req.body.password;
            const isMatch = await bcrypt.compare(password, customer.password);
            if (!isMatch) {
                throw new Error('The username or password you entered does not match any account');
            }
            return true
            })
            .run(req)
        
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            const alert = errors.array();
            return res.render('./customer/login', { alert, session: req.session });
        }
        const username = req.body.username
        const customer = await Customer.findOne({username})
        req.session.isAuth = true
        req.session.username = username
        req.session.isAdmin = customer.admin
        return res.redirect('/')
    } catch (error) {
        console.log(error);
    }
}

以防万一下面是我的注销路线。

exports.logoutCustomer =  async (req, res) => {
    req.session.destroy((err) => {
        if (err) {
            throw err
        } else {
            console.log("LOGOUT")
            res.redirect('../')
        }
    })
}

问题是当用户在注销后成功重新登录时,session.isAuth 和 session.username 的设置不一致。我已经测试了很多次登录注销然后重新登录,发现有时这些值设置正确,有时却没有。但是,我注意到在用户成功登录但无法呈现这两个值后,如果我刷新页面,我可以呈现这些值。

感谢您的任何意见、想法和建议。

我尝试更改代码行的顺序并检查是否通过呈现这两个值(使用 ejs)设置了 session.isAuth 和 session.username。然而,我发现它们并没有得到一致的渲染。

javascript node.js express session ejs
© www.soinside.com 2019 - 2024. All rights reserved.