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

使用Node.js与node-postgres访问PSQL数据库时遭遇ECONNREFUSED错误

问题:GET请求获取数据库条目时出现连接拒绝错误

当通过浏览器发起GET请求获取数据库表所有条目时,收到以下错误:

Error: connect ECONNREFUSED 127.0.0.1:5432
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1187:16)
Error in GET /products

项目文件夹结构

server/
  db/
    index.js
  routes/
    products.js
  index.js

涉及文件内容

server/index.js

该文件用于在3001端口初始化服务器并挂载productsRouter:

const express = require("express");
const cors = require("cors");
const app = express();

const PORT = process.env.port || 3001;

app.use(cors());
app.use(express.json());

// const usersRouter = require('./routes/users')
// app.use('/users', usersRouter)
// const authRouter = require('./routes/auth')
// app.use(['/login', '/register'], authRouter)
const productsRouter = require('./routes/products')
app.use('/products', productsRouter)
// const cartsRouter = require('./routes/carts')
// app.use('/carts', cartsRouter)
// const ordersRouter = require('./routes/orders')
// app.use('/orders', ordersRouter)

app.listen(PORT, () => {
  console.log(`Listening on ${PORT}`);
});

server/db/index.js

该文件提供执行数据库查询的函数:

const { Pool, Client } = require("pg");

const pool = new Pool({
  user: "postgres",
  host: "localhost",
  database: "ecommerce",
  password: "postgres",
  port: "5432",
});

module.exports = {
  query: (text, params, callback) => {
    return pool.query(text, params, callback)
  },
}

server/routes/products.js

该文件包含发起数据库查询的Node.js逻辑:

const express = require("express");
const products = express.Router();
const db = require("../db/index");

products.get("/", async (req, res) => {
  try {
    const products = await db.query("SELECT * FROM products");
    return res.status(201).send(products.rows);
  } catch (err) {
    console.log(err.stack);
    console.log("Error in GET /products");
    res.status(500).send("Server Error Occurred");
  }
});

错误复现步骤

  • 在localhost的5432端口启动/连接Postbird
  • 进入server/index.js所在目录,执行node index.js启动监听3001端口的Node.js服务器
  • 在浏览器中访问localhost:3001/products发起GET请求

解决方案

1. 确认PostgreSQL服务正在运行

ECONNREFUSED错误说明Node.js无法连接到5432端口的PostgreSQL服务,Postbird只是客户端工具,必须确保PostgreSQL服务器本身处于运行状态:

  • Windows:打开服务管理器,找到postgresql-x64-xx服务,确认状态为“正在运行”
  • macOS:执行brew services list查看postgresql状态,若未运行则执行brew services start postgresql
  • Linux:执行sudo systemctl status postgresql,若未运行则执行sudo systemctl start postgresql

2. 修正数据库连接配置

  • 将server/db/index.js中的port参数改为数字类型(当前为字符串"5432"):
    const pool = new Pool({
      user: "postgres",
      host: "localhost",
      database: "ecommerce",
      password: "postgres",
      port: 5432, // 改为数字
    });
    
  • 验证数据库ecommerce是否存在,可通过Postbird连接后查看数据库列表
  • 确认用户名postgres和密码postgres与PostgreSQL的实际配置一致

3. 测试数据库连接

在server/db/index.js中添加测试代码,验证连接是否正常:

pool.connect((err, client, release) => {
  if (err) {
    return console.error('连接数据库失败', err.stack)
  }
  console.log('数据库连接成功')
  release()
})

重新启动Node.js服务器,查看控制台输出是否有连接成功的提示。

4. 确认端口未被占用

执行lsof -i :5432(macOS/Linux)或netstat -ano | findstr :5432(Windows),确认5432端口被PostgreSQL占用,而非其他程序。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 08:55:17