node.js - 使用多个参数 Node.js 查询 Postgres
问题描述
我刚从 Node.js 开始Node.js
用 db 构建服务器Postgres
,我已经为 CRUD 操作准备了一些路由和方法:
router.get('/products', productController.listAllProducts);
exports.listAllProducts = async (req, res) => {
const response = await db.query('SELECT * FROM products ORDER BY productName ASC');
if (response.rowCount > 0) {
res.status(200).send(response.rows);
} else {
res.status(404).send({
message: "No products found"
});
}
};
在 Postman 中,urllocalhost:3000/api/products
工作得很好。现在我试图在查询中包含 3 个参数city
,region
并且country
router.get('/products', productController.findCityProducts); // correct route??
exports.findCityProducts = async (req, res) => {
const city = req.query.city;
const region = req.query.region;
const country = req.query.country;
const response = await db.query('SELECT * FROM products WHERE city = $1 AND region = $2 AND country = $3', [city,region,country]);
if (response.rowCount > 0) {
res.status(200).send(response.rows);
} else {
res.status(404).send({
message: 'Product not found'
});
}
};
在 Postman 中,我添加了 3 个参数,因此 url 是localhost:3000/api/products?city=Bologna®ion=Emilia-Romagna&country=Italy
但结果与listAllProducts
方法相同。并且没有满足查询的记录。所以我猜到'/products' route can't have more than one method assigned..and is calling
listAllProducts ..I commented it out and indeed now is calling
findCityProduct`。
我将如何同时启用listAllProducts
和findCityProduct
查询?非常感谢。
解决方案
正如您所发现的,您不能使用不同的控制器函数(listAllProducts、findCityProducts)定义具有相同路径和 HTTP 方法(GET /products)的两条路由。
您可以在此处采用的一种简单方法是根据 URL 中参数的存在来调整您的控制器函数以使其行为不同。
此外,值得注意的是,您应该在 SQL 查询中使用任何外部输入之前对其进行清理,以避免注入。
router.get('/products', productController.listProducts);
exports.listProducts = async (req, res) => {
const { city, region, country } = req.query
let response
if (city && region && country) {
response = await db.query('SELECT * FROM products WHERE city = $1 AND region = $2 AND country = $3', [city,region,country]);
} else {
response = await db.query('SELECT * FROM products ORDER BY productName ASC');
}
if (response.rowCount > 0) {
res.status(200).send(response.rows);
} else {
res.status(404).send({ message: "No products found" });
}
};
推荐阅读
- python - Pandas:基于两个不同的列创建唯一值的索引
- c - 我正在尝试在 C 中制作 fork() 进程调用图
- sql-server - 如何从 ADF 传递 SQL 中 TABLE VALUE TYPE 中的可选列
- java - 我怎样才能实现java接口到java类
- azure-devops - 在 Azure DevOps 版本中使用 ask deploy 时出错
- c - 如何减少这段代码以避免TLE
- linux - 如何通过 rc.local 重启 Linux 中的后台进程?
- typescript - 在Vue中创建v-select菜单时动态推送新数据集
- javascript - JS Discord Bot - 创建具有特定权限的频道 ( v12+ )
- python - 启用 CORS 谷歌云函数 (Python)