我是一个有用的助手,可以翻译文本。
我在我的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"
问题
- 为什么直接传递参数不能返回适当的记录,而传递其字符串等效项可以返回适当的记录?
url = 'http://.../?destination=' + encodeURIComponent(destination)
。 - ForbesLindesay