Conditional app.use in node - express

Conditional app.use in node - express

本文关键字:express node in app use Conditional      更新时间:2023-09-26

是否可以在app.js中有条件地使用app.use?快速cookie会话无法动态更改maxAge的值,我曾想过做这样的事情,但我遇到了一些错误:

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']
}));

现在我得到以下错误:

无法读取未定义的属性"user"

我相信它指的是这条线(尽管它没有说具体在哪里)

req.session.user;

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);
});

您可以使用此插件Express Conditional Tree中间件。

它允许您组合多个和异步中间件。看看吧!您可以创建两个类(一个用于第一种情况,一个用于第二种情况),分别在applyMiddleware函数中编写代码,然后将这些类导入主javascript文件中,并使用orChainer将它们组合起来。有关更多信息,请参阅文档!