连接Redis不保留数据

axzmvihb  于 2023-05-28  发布在  Redis
关注(0)|答案(1)|浏览(151)

我正在使用 *Node. jsinAction * 中的一个示例,但在使用它时遇到了问题。下面是我的代码:

var connect = require('connect');
var RedisStore = require('connect-redis')(connect);

var app = connect();
app.use(connect.favicon());
app.use(connect.cookieParser('Cereal killin keybored kittty'));
app.use(connect.session({
  store: new RedisStore({prefix: 'boom'})
}));
app.use(function (req, res, next) {
  console.log(req.session);
  if (req.session.views) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('<p>views: ' + req.session.views  + '</p>');
    res.write('<p>expires in: ' + req.session.cookie.maxAge + '</p>');
    res.write('<p>httpOnly: ' + req.session.cookie.httpOnly + '</p>');
    res.write('<p>path: ' + req.session.cookie.path + '</p>');
    res.write('<p>domain: ' + req.session.cookie.domain + '</p>');
    res.write('<p>secure: ' + req.session.cookie.secure + '</p>');
    res.end();
    req.session.views += 1;
  } else {
    req.session.views += 1;
    res.end('Welcome to the session demo. Refresh the page.');
  }
}).listen(3000);

无论我刷新多少次,req.session.views都保持等于1。任何帮助都会摇滚!

j7dteeu8

j7dteeu81#

尝试在更改会话后显式保存会话:

...
  req.session.views += 1;
} else {
  req.session.views += 1;
  res.end('Welcome to the session demo. Refresh the page.');
}
req.session.save();
...

我认为唯一不需要显式save()的存储是MemoryStore(刚刚检查了 * Node.js in Action* 的示例代码,它也使用了MemoryStore)。

相关问题