Nodejs 全局中间件

Nodejs Global middleware

我们如何将中间件添加到 app.use() 并仅在我们调用它时使用该中间件。目前我有这个代码:

function ensureUser(req,res,next){
   if(req.isAuthenticated()) next();
   else res.send(false);
}
app.get('/anything', ensureUser, function(req,res){
    // some code
})

我正在尝试将该 ensureUser 添加到我有路由的所有文件中。我提出了一种解决方案,将该文件添加到一个文件中,并在我有路由的每个文件中都需要该文件。有没有办法将该功能添加到 app.useapp.all 或类似的东西,这样我就不必在每个文件中都包含该功能。

是的,在没有第一个参数的任何路由之前添加 app.use() ,并且应该始终调用该参数:

app.use(function(req, res, next){
  if(req.isAuthenticated()) next();
  else res.send(false);
});

// routing code
app.get('/', function(req, res){});
app.get('/anything', function(req,res){})
//...

这样您就不必在每个文件中都包含它。但是,通过这种方式,您还需要对每个文件进行身份验证,因此您可能想要添加一些例外情况(至少是身份验证页面)。为此,您可以在 url with a wildcard:

中包含该方法
app.use('/admin/*', function(req, res, next){
  if(req.isAuthenticated()) next();
  else res.send(false);
});

或者在函数内部添加白名单:

app.use(function(req, res, next){
  // Whitelist
  if(['/', '/public'].indexOf(req.url) !== -1
     || req.isAuthenticated())
    next();

  else
    res.send(false);
}