运行 许多 Express.js 路线开头的相同代码

Running the same code at the beginning of many Express.js routes

查看这些路线:

app.get('/', function (req, res) {
    var legacy = false;
    //LENGTHY CODE that sets legacy to true for old browsers

    if (legacy === false) {
        res.render('home');
    } else {
        res.render('legacy');
    }
});

app.get('/other', function (req, res) {
    var legacy = false;
    //LENGTHY CODE that sets legacy to true for old browsers

    if (legacy === false) {
        res.render('other');
    } else {
        res.render('legacy');
    }
});

//Many other routes like this with the legacy check.

问题是,如何避免在每条路线中重复冗长的代码?将它放入一个函数中并不是真正的解决方案,因为这回避了一个问题,我如何避免在每个路由中调用该函数?

有什么好的解决办法吗?

也许这就是所谓的中间件?

不胜感激。

是的,正如您所说,这正是中间件的用途。

app.use(function (req, res, next) {
   var legacy = false;
   if (legacy) {
       res.render('legacy');
   } else {
       next();
   }
});

您可以使用 next()。 试试这个:

app.get(['/', '/other'], function(req, res, next){                                      
  //preprocessing here                     
  next();                                                                   
});  

它接受路径、路径模式、正则表达式和数组。 如果您不希望某些路径执行此预处理,那么您可以使用正则表达式来否定这些路径。