You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js非Sequelize查询location表遇Cannot read properties of undefined错误

解决PostgreSQL查询中"Cannot read properties of undefined (reading 'rows')"错误

你遇到的错误:

error: Cannot read properties of undefined (reading 'rows')

核心原因

调用client.query时参数传递错误:该方法的第二个参数要求是包含所有占位符对应值的单个数组,但你传入了两个独立的数组。这会导致查询执行失败,返回的location为undefined,读取rows属性时就会触发上述错误。

修复后的代码

const client = require('../../db')
const express = require('express');
const app = express();
const cors = require("cors");

app.use(cors());
app.use(express.json()); // 解析JSON请求体

app.listen(8670, ()=>{
    console.log("Server is now listening at port 8670"); // 修正端口号不一致的笔误
})

client.connect();

app.get("/location", async (req, res) => {
    try {
      // 给查询参数设置默认值,避免未传参时出现undefined
      const { city = '', district = '' } = req.query;
      // 将两个查询条件合并到同一个参数数组中
      const location = await client.query(
        'SELECT * FROM location WHERE city ILIKE $1 AND district ILIKE $2',
        [`%${city}%`, `%${district}%`]
      );
      res.json(location.rows);
    } catch (err) {
      console.error(err.message);
      // 给客户端返回500错误响应,避免请求挂起
      res.status(500).json({ error: err.message });
    }
});

优化说明

  1. 修正了日志中的端口号错误:监听端口是8670,原日志误写为5000,保持一致减少排查困惑
  2. 给city和district设置空字符串默认值,防止未传参时生成%undefined%这类无效的模糊查询条件
  3. 新增错误响应返回,确保客户端能收到错误信息,而非无响应

内容的提问来源于stack exchange,提问作者Ecren

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 11:05:17