我是Node JS和Express JS的初学者。我正在创建一个API,该API使用具有两个参数的请求URL http://localhost:3000/?term=jerry&city=dublin。我可以使用req.query获得这些值。我希望城市是可选的。如果没有城市的值,则查询应该可以正常工作。我该如何实施?我希望以这种方式处理多个参数。例如。我希望参数'term'在请求http://localhost:3000/?term=jerry&city=dublin&age=25&profession=student中是必需的,而其他所有术语则是可选的。我的数据库是 postgres ,当多个参数为可选参数且未输入这些参数的值时,我该如何处理。是否应基于参数值修改查询?对于未随请求URL发送的参数,我得到“未定义”,但查询无法实现。有人可以帮助我提供与此相关的最佳做法吗?我能够找到使用req.params处理查询的结果。
在我处理请求的地方添加方法:
router.get('/', function (req, res) {
var db = require('./db');
console.log(req.query.term);
console.log(req.query.country);
var term = req.query.term;
var country = req.query.country;
db.any('SELECT s.official_title, e.gender, e.criteria, fc.name, fc.email, fc.phone, f.country, c.name, c.downcase_name FROM eligibilities AS e LEFT JOIN studies AS s ON e.nct_id = s.nct_id LEFT JOIN facility_contacts AS fc ON fc.nct_id = s.nct_id LEFT JOIN facilities AS f ON f.nct_id = s.nct_id LEFT JOIN conditions AS c ON c.nct_id = s.nct_id GROUP BY s.official_title, e.gender, e.criteria, fc.name, fc.email, fc.phone, f.country, c.name, c.downcase_name HAVING c.downcase_name LIKE $1 AND f.country LIKE $2 LIMIT 10', ['%' + term + '%', '%' + country + '%']).then(function(data) {
return res.status(200).send(data);
}).catch(function(error) {
return res.status(500).send("There was an error");
});
});