使用动态路由时,中间件功能被执行多次而不是一次

Middleware function is executed multiple times rather than just once when using dynamic routes

我有这个中间件:

app.use((req, res, next) => {
  console.log('test');
  next();
});

我有这些动态路线:

app.get('/:path', (req, res, next) =>{
  var pages = serverCache.pages;
  for (let page of pages) {
    if(req.params.path === page.path){
      res.render('foo', {
        helpers:helpers
      });
      return;
    }//if
  }//for
  res.redirect('/');
});

加载页面时,我希望 console.log('test') 只执行一次。但是它被执行了很多次。实际输出为:

test
test
test
test
...

它的发生是因为它在 for 循环中的每个迭代中执行。仅当该循环内的 if 语句条件为真时,我如何执行它?

o(1 + count of pages verifying the condition).

验证引擎盖下发生的事情的最简单方法是调试你的 nodejs 应用程序,你不能像下面那样在两者之间放置一些日志

app.get('/:path', (req, res, next) =>{
  console.log('Get/:path'); //NOTICE HERE
  var pages = serverCache.pages;
  for (let page of pages) {
    if(req.params.path === page.path){
      console.log('rendering foo'); //NOTICE HERE
      res.render('foo', {
        helpers:helpers
      });
      return;
    }//if
  }//for
  console.log('redirecting to /'); //NOTICE HERE
  res.redirect('/');
});

我误解了函数什么时候执行。

之所以执行了多次,是因为它为它检查的每条路由执行了自己。 (对于之后的所有中间件功能)

为了让它只对我的动态路由执行,我将这两个函数都移到了底部。

app.get('static route')
app.post('static route')
app.use('static route')
app.use(); // moved it here
app.get('dynamic route')