首页 > 解决方案 > 使用多个参数 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 个参数cityregion并且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&region=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`。

我将如何同时启用listAllProductsfindCityProduct查询?非常感谢。

标签: node.jspostgresql

解决方案


正如您所发现的,您不能使用不同的控制器函数(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" });
  }
};

推荐阅读