我是用 express 建站的,我有一个特殊的要求,我把路由器设置如下:
/* home */
app.get('/', function (req, res, next) {
homeRacingHandle(req,res);
});
/* racing list */
app.get('/racing',function (req, res, next) {
homeRacingHandle(req,res);
});
home page 之间只有一些不同之处。和 racing list page .
我处理公共(public)逻辑的方法如上。homeRacingHandle函数根据变量isHome
来决定渲染哪个页面。
var location = req.path.split('?').toString();
var isHome = location==='/' && true || false;
这个方法对我有用。但我不知道这是不是一个好的处理方法。还有其他最佳实践吗?
最佳答案
你可以使用柯里化(Currying)来简化这个
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
}
}
关于javascript - 如何在 Express.js 中共享 Controller 之间的通用逻辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33005685/