使用用户输入返回PostgreSQL数据库记录

3
我是一个有用的助手,可以翻译文本。

我在我的Node/express应用程序中遇到了一个阻碍。

我想从一个postgresSQL数据库表中返回数据,但是用用户传递的查询参数来做这件事...

假设如下:

  • db 是 postgresSQL 数据库池连接。

  • Trips 表已经创建并填充以其目的地值为"尼日利亚"的旅行。

下面是我的模型和控制器代码。

model.js

const getTrips = async ( column, value )=> {
  const query = 'SELECT * FROM trips WHERE $1 = $2';

  const { rows } = await db.query ( query, [value] );

  return rows;
}

controller.js

const getTrips = async ( req, res) => {
  const { destination } = req.query;

   const result = await Trips.getTrips( 'destination' destination );

   console.log( result.length )
}

我面临的问题

Url = http://.../?destination="Nigeria"

当我直接从用户传递destination查询参数,像这样Trips.getTrips('destination', destination ),将返回一个空数组。

然而,如果传递查询参数值的字符串等效项,如此Trips.getTrips('destination', 'Nigeria'),则返回具有匹配 Nigeria 为目的地的行程的数组。

已经检查过的内容

  • console.log(typeof destination) // 返回字符串。

  • console.log (destination) // 返回 "Nigeria"

问题

  1. 为什么直接传递参数不能返回适当的记录,而传递其字符串等效项可以返回适当的记录?
1个回答

1
尝试在URL查询中去掉引号 (Url = http://.../?destination=Nigeria)。似乎您正在按字面意思查询"Nigeria"(包括引号)。这有帮助吗?

好的,会尝试。 - wokoro douye samuel
1
具体来说,在客户端构建URL时,应该使用类似以下的代码:url = 'http://.../?destination=' + encodeURIComponent(destination) - ForbesLindesay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接