【问题标题】:Renewing Cookie-session for express.js为 express.js 更新 Cookie-session
【发布时间】:2016-01-15 02:51:58
【问题描述】:

我正在使用 Expresss.js 的 cookie-session 模块来处理会话。

我希望在每次页面加载(或 ajax 调用)时更新会话。这就是他们通常在任何地方工作的方式。

文档只字未提。

我试过这样做,但没有成功:

app.use(function(req,res,next ){
     req.sessionOptions.maxAge = 20*1000;
     return next();
});

【问题讨论】:

    标签: node.js express express-session


    【解决方案1】:

    我怀疑您没有将响应 cookie 发送给客户端。我用一个中间件解决了同样的问题(使用 express 和 cookie-session),该中间件为每个 get 发送一个包含不同值的 cookie:

    var cookieSession = require('cookie-session') 
    
    app.use(cookieSession({
      key: cookieKey,
      secret: cookieSecret,
      maxAge: 1 * 60 * 60 * 1000 // 1 hour (rolling)
      })
    );
    
    app.get('*', function(req, res, next) {
      // To update the session expiration time we need to send the new
      // expiration in the response cookie.
      // To send again the response cookie to the client we need to
      // update the session object.
      req.session.fake = Date.now();
      next();
    });
    

    确实,如果会话对象does not change,cookie-session v. 1.2.0 并没有set the Set-Cookie header 将响应cookie 发送给客户端。

    【讨论】:

    • 为什么我们需要设置一个新值的fake会话?
    • 编辑了响应以明确为什么需要更改会话对象。
    • 那么更新cookie的唯一方法就是改变它的一些属性?只要我被允许这样做,我就会接受答案。需要 24 小时。
    猜你喜欢
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    • 2014-09-15
    • 2012-12-07
    • 1970-01-01
    • 2020-05-12
    • 2012-02-09
    • 2023-03-03
    相关资源
    最近更新 更多