在 Node.js 和 express-session 中更改和刷新会话数据 [英] change and refresh session data in Node.js and express-session

查看:78
本文介绍了在 Node.js 和 express-session 中更改和刷新会话数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Node.js 以及 express-session 和我有这个保存用户信息的会话数据

I'm using Node.js along with express-session and I've got this session data that holds the user information

req.session.user

现在当用户更新信息时,我将会话设置为新数据,然后重新加载

now when the user updates the information, I set the session to the new data and then reload it

req.session.reload(function(err) {
req.session.user = user;
});

它应该可以工作但 req.session.user 仍然显示旧信息,为什么?:(
非常感谢提前

it should work but the req.session.user still shows the old information, why? :(
many thanks in advance

推荐答案

您在保存更改之前正在重新加载.保存通常在请求结束时自动发生.session.js 中有一个测试演示了这种行为.

You are reloading before saving your change. Saving usually happens at the end of the request automatically. There is a test in session.js which demonstrates that behaviour.

使用 req.session.reload() 还原当前在处理请求时所做的更改...

Using req.session.reload() reverts the changes that currently have been been made while processing the request ...

req.session.example = 'set on set_reload'
req.session.reload( function (err) {
    res.render('index', { title: req.session.example });
});
// next http get request
// req.session.example == value before the call above 

考虑像这样使用会话

req.session.example = 'set on set';
res.render('index', { title: req.session.example });
// next http get
// req.session.example == 'set on set'

如果您有使用 req.session.reload() 的真正原因,那么这种类型的用法将为您提供所需的行为

If you have a real reason for using req.session.reload() then this type of usage will give you the desired behaviour

req.session.example = 'set on set_save_reload';
req.session.save( function(err) {
    req.session.reload( function (err) {
         res.render('index', { title: req.session.example });
    });
});
// next http get
// req.session.example == 'set on set_save_reload'

这篇关于在 Node.js 和 express-session 中更改和刷新会话数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆