![](/img/trans.png)
[英]How to pass additional parameters to an encapsulated callback function in node.js
[英]Node + Callback function pass parameters
我正在使用express节点。
我有两个rest api,两者之间的区别仅在于数据库表而已。
API-1个http:// localhost / test1
API-2 http:// localhost / test2
两者都是发布方法,
router.post('test1', findAll);
router.post('test2', findAll);
function findAll(req, res){
//Here test1 api result get from different db table.
//Here test2 api result get from different db table.
How can I sent the db table name in parameters?
//Here have logic in db and return results.
res.send(spec.resp);
}
注意:我需要对两个api使用相同的函数,但是表名将被更改。
您可以创建两个利用常见的findAll
方法的函数,如下所示:
function findAllFromTable1(req, res, next){
return findAll("table1", req, res, next);
}
function findAllFromTable2(req, res, next){
return findAll("table2", req, res, next);
}
function findAll(tableName, req, res, next){
//db logic
res.send(spec.resp);
}
router.post('test1', findAllFromTable1);
router.post('test2', findAllFromTable2);
但是我建议您将db逻辑与路由处理程序分开,因此,要有一个处理db并发回响应的函数,而要有一个包含db逻辑的函数,然后在路由句柄中使用该结果发送响应。 这将使您的代码易于理解,易于测试并避免冗余。
function findAllFromDB(){
//db logic
return dbResult; // returns a promise since db operations are async.
}
router.post('test1', function(req, res, next){
findAllFromDB
.then(function(dbResult){res.send(dbResult)})
.catch(function(err){ res.status(500).send(err);})
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.