如何在Express.js中共享控制器之间的通用逻辑?

我用快递来build立我的网站,我有一个特殊的要求。我设置了路由器如下:

/* home */ app.get('/', function (req, res, next) { homeRacingHandle(req,res); }); /* racing list */ app.get('/racing',function (req, res, next) { homeRacingHandle(req,res); }); 

主页和赛车列表页面之间只有几个不同的地方。 我的处理公共逻辑的方法如上所述。homeRacingHandle函数根据variablesisHome决定要渲染哪个页面。

  var location = req.path.split('?').toString(); var isHome = location==='/' && true || false; 

这种方法适用于我。但我不知道这是一个好的处理方法。还有其他的最佳做法吗?

你可以使用咖喱来简化这个

 curryHomeRacing = require('./handler'); /* home */ app.get('/', curryHomeRacing('home')); /* racing list */ app.get('/racing', curryHomeRacing('racing')); 

在另一个文件handler.js中

 //in handler.js module.exports = function curryHomeRacing(route){ return function(req, res) { homeRacingHandle(req, res, route); }; } function homeRacingHandle(req, res, route) { if (route === 'home') { //do home stuff } else if (route === 'racing') { //do racing stuff } }