我正在使用带有express的 Node 。
我有两个rest api,api之间的区别只是数据库表而已。
API - 1 <强> http://localhost/test1
API - 2 <强> http://localhost/test2
两者都是post方法,
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);
但是我建议您将数据库逻辑与路由处理程序分开,因此使用一个包含数据库逻辑的函数来代替处理数据库并将响应发回的函数,然后在路由句柄中使用该结果发送您的响应。这将使您的代码易于理解、易于测试并避免冗余。
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);})
});
关于javascript - Node +回调函数传参,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42455855/