我的API端点未返回预期的输出

时间:2019-08-18 15:44:53

标签: javascript node.js postgresql api express

我已经用Express JS编写了一个后端应用程序,以通过API端点的GET请求从数据库中检索信息。我曾经从API端点获取的查询正在数据库中运行,但是我无法在Web浏览器中获取与使用Express JS的响应相同的详细信息。尽力找出问题所在,但未能成功。

我试图检查我的查询是否有问题,但是查询获取的是正确的详细信息,但是我无法在网络浏览器中得到任何答复。

这是我认为存在错误的代码:

      const { rows } = await pool.query(
                'SELECT  branches.ifsc, branches.bank_id, branches.branch, branches.address, branches.city, branches.district, branches.state FROM branches WHERE branches.branch LIKE $1% LIMIT $2 OFFSET $3' ,

        [q, limit, offset]
      );

      res.send(rows[0]);
    });

用于获取详细信息的SQL查询:

    SELECT branches.ifsc, branches.bank_id, branches.branch, branches.address, branches.city, branches.district, branches.state FROM branches WHERE branches.branch LIKE '%RTGS%' ORDER BY branches.ifsc LIMIT 3;

错误日志:

Server is running on 7000
(node:19484) UnhandledPromiseRejectionWarning: error: syntax error at or near "LIMIT"
    at Connection.parseE (/home/kiddo/Desktop/backend/node_modules/pg/lib/connection.js:604:11)
    at Connection.parseMessage (/home/kiddo/Desktop/backend/node_modules/pg/lib/connection.js:401:19)
    at Socket.<anonymous> (/home/kiddo/Desktop/backend/node_modules/pg/lib/connection.js:121:22)
    at Socket.emit (events.js:200:13)
    at addChunk (_stream_readable.js:294:12)
    at readableAddChunk (_stream_readable.js:275:11)
    at Socket.Readable.push (_stream_readable.js:210:10)
    at TCP.onStreamRead (internal/stream_base_commons.js:166:17)
(node:19484) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:19484) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

2 个答案:

答案 0 :(得分:0)

尝试使用回调功能。

con.query("YOUR SQL QUERY HERE", function (err, result, fields) {
    if (err) throw err;
    console.log(result);
  });

参数替换示例

     var sql = "SELECT * FROM table WHERE field1 = ? AND field2 >= ?";
connection.query(sql, [value1, value2], function(err, result, fields) {
    //do your operations HERE
    console.log(result);

});

答案 1 :(得分:0)

我怀疑使用$1%会导致您的sql语句出现问题。请尝试以下方法。

const { rows } = await pool.query(
        'SELECT  branches.ifsc, branches.bank_id, branches.branch, branches.address, branches.city, branches.district, branches.state FROM branches WHERE branches.branch LIKE $1 LIMIT $2 OFFSET $3' ,
['%'+q+'%', limit, offset]);