【问题标题】:Returning posgreSQL database records with user input使用用户输入返回 postgreSQL 数据库记录
【发布时间】:2019-11-23 07:36:00
【问题描述】:

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

我想从 postgresSQL 数据库表中返回数据,但是使用用户传递的查询参数...

假设如下:

  • db 是一个 postgresSQL 数据库池连接。

  • 行程表已创建并填充了目的地值为“尼日利亚”的行程。

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

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'),则会返回一个数组,其中包含匹配尼日利亚作为目的地的 Trips。

检查完毕

  • console.log(typeof destination) // returns string.

  • console.log (destination) // returns "Nigeria"

问题

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

【问题讨论】:

    标签: node.js postgresql express


    【解决方案1】:

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

    【讨论】:

    • 好的。会尝试的。
    • 特别是在客户端构建 URL 时,您应该使用类似:url = 'http://.../?destination=' + encodeURIComponent(destination)
    猜你喜欢
    • 2012-03-08
    • 1970-01-01
    • 2019-02-14
    • 2019-03-05
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 2015-09-28
    相关资源
    最近更新 更多