我想简化一段我的代码,但不确定如何做。我有
// Monitoring route
app.get('/ping', (req, res)=>{
res.send('Hello World!');
})
// Route that receives a GET
app.get('/getCar', (req, res)=>{ routes.get(req, res);})
app.get('/getCarList', (req, res)=>{ routes.get(req, res);})
app.get('/getDriver', (req, res)=>{ routes.get(req, res);})
app.get('/getDriverList', (req, res)=>{ routes.get(req, res);})
app.get('/getCarDriver', //do something else than the rest)
所以我想让这四个应用一起做同样的事情。我开始考虑为结果做一个函数,如下所示:
var getSendRes = (req, res)=>{ routes.get(req, res);}
但我认为如果我把所有的应用程序合并在一起做同样的事情会更好。知道吗?
谢谢,
一种选择是绑定routes.get
函数,这样每次都可以引用它,而不是键入它:
const getBound = routes.get.bind(routes);
app.get('/getCar', getBound);
app.get('/getCarList', getBound);
// etc
如果您有一大堆,您可以迭代一个数组的路由字符串:
for (const str of ['getCar', 'getCarList', 'getDriver', 'getDriverList']) {
app.get('/' + str, (req, res) => { routes.get(req, res); }
}