【问题标题】:Conditional app.use in node - express节点中的条件 app.use - express
【发布时间】:2017-09-15 19:07:47
【问题描述】:

是否可以在 app.js 中有条件地使用app.use? Express cookie-session 可以 not change the value of maxAge dynamically 并且我正在考虑做这种事情,但我遇到了一些错误:

app.use(function(req,res,next ){
  if(typeof req.session == 'undefined' || req.session.staySignedIn === 'undefined'){
    //removing cookie at the end of the session
    cookieSession({
      httpOnly: true,
      secure: false,
      secureProxy: true,
      keys: ['key1', 'key2']
    });
  }else{
    //removing cookie after 30 days
    cookieSession({
      maxAge: 30*24*60*60*1000, //30 days
      httpOnly: true,
      secure: false,
      secureProxy: true,
      keys: ['key1', 'key2']
    });
  }
  next();
});

而不是正常使用它:

app.use(cookieSession({
  httpOnly: true,
  secure: false,
  secureProxy: true,
  keys: ['key1', 'key2']
}));

现在我收到以下错误:

无法读取未定义的属性“用户”

我相信它指的是这条线(虽然它没有说明确切的位置)

req.session.user;

【问题讨论】:

    标签: javascript node.js express cookie-session


    【解决方案1】:

    Express 中的中间件是一个函数,例如function (req, res, next) {}。在您的示例中,cookieSession(options) 将返回这样一个函数,但在您的中间件中您不运行它,您忽略了 cookieSession 的返回值 - 即您要运行的中间件。然后你运行next()

    您想要做的是在您的(我们称之为条件中间件)中执行实际的中间件。像这样的:

    app.use(function (req, res, next) {
      var options = {
        httpOnly: true,
        secure: false,
        secureProxy: true,
        keys: ['key1', 'key2']
      };
    
      if(typeof req.session == 'undefined' || req.session.staySignedIn === 'undefined') {
        options.maxAge = 30*24*60*60*1000; // 30 days
      }
    
      return cookieSession(options)(req, res, next);
    });
    

    【讨论】:

    • 让我印象深刻的是,在每个请求上初始化会话中间件可能不是一个好主意。我不太确定这个解决方案,您可能需要一种完全不同的方法。我不清楚为什么不能为单个 cookie 设置 maxAge?例如。 req.cookie.maxAge = 12345...我很确定它在过去有效?
    • 查看此对话:github.com/expressjs/cookie-session/issues/… 似乎不可能。
    【解决方案2】:

    你可以使用这个插件Express Conditional Tree Middleware

    它允许您组合多个异步中间件。一探究竟!您可以创建两个类(一个用于您的第一个案例,一个用于您的第二个案例),分别在applyMiddleware 函数中编写代码,然后将这些类导入您的主 javascript 文件中并使用 orChainer 组合它们。有关详细信息,请参阅文档!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-11
      • 1970-01-01
      • 1970-01-01
      • 2015-01-29
      • 1970-01-01
      • 2019-07-22
      • 1970-01-01
      • 2012-07-04
      相关资源
      最近更新 更多