连接Redis不保留数据

时间:2013-12-02 19:39:15

标签: javascript node.js redis connect

我正在关注 Node.js in Action 中的示例,但我无法让它工作。这是我的代码:

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.任何帮助都会摇滚!

1 个答案:

答案 0 :(得分:1)

尝试在更改后明确保存会话:

  ...
  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)。