命令行可连PostgreSQL但Node.js连接失败问题求助
问题描述
我能通过命令提示符执行psql -h localhost -p 5432 -U postgres -d Luxe-Hotel并输入密码连接PostgreSQL数据库,但Node.js代码无法建立连接。
Node.js 连接代码
import express from "express"; import cors from "cors"; import pkg from "body-parser"; import bcrypt from "bcrypt"; import knex from "knex"; import handleRegistration from "./controllers/handleRegistration.js"; import handleSignIn from "./controllers/handleSignIn.js"; const db = knex({ client: 'pg', connection: { host: 'localhost', port: 5432, user: 'postgres', password: 'xxxxxxxxxx', database:'Luxe-Hotel' }, pool: { min: 0, max: 7 } }); db.raw('SELECT 1') .then(() => console.log('PostgreSQL connected')) .catch(err => console.error('PostgreSQL connection error:', err));
启动服务器后收到的错误
PostgreSQL connection error: AggregateError [ECONNREFUSED]: at internalConnectMultiple (node:net:1122:18) at afterConnectMultiple (node:net:1689:7) { code: 'ECONNREFUSED', [errors]: [ Error: connect ECONNREFUSED ::1:5432 at createConnectionError (node:net:1652:14) at afterConnectMultiple (node:net:1682:16) { errno: -111, code: 'ECONNREFUSED', syscall: 'connect', address: '::1', port: 5432 }, Error: connect ECONNREFUSED 127.0.0.1:5432 at createConnectionError (node:net:1652:14) at afterConnectMultiple (node:net:1682:16) { errno: -111, code: 'ECONNREFUSED', syscall: 'connect', address: '127.0.0.1', port: 5432 } ] }
已尝试关闭防火墙、检查PostgreSQL监听地址和端口、核对代码配置,问题仍未解决。
排查与解决建议
- 将连接配置中的
host从localhost改为127.0.0.1或PostgreSQL实际绑定的IP地址。部分环境中localhost会优先解析到IPv6的::1,若PostgreSQL仅监听IPv4的127.0.0.1,就会出现连接拒绝的情况。 - 检查PostgreSQL的pg_hba.conf文件,确认是否允许
postgres用户从127.0.0.1或::1进行密码认证。psql可能使用本地套接字连接而非TCP/IP,因此即使psql能连,TCP/IP的认证规则可能仍不匹配。可添加或确认如下规则:
修改后需重启PostgreSQL服务生效。host all postgres 127.0.0.1/32 scram-sha-256 host all postgres ::1/128 scram-sha-256 - 验证knex版本与PostgreSQL版本的兼容性。旧版本knex可能与新版本PostgreSQL存在连接逻辑冲突,尝试升级knex至最新稳定版:
npm install knex@latest - 用底层
pg包编写极简测试代码,排除knex配置问题:
若此代码能连接,说明问题出在knex配置;若仍无法连接,继续排查系统TCP/IP连接层面的问题。import { Client } from 'pg'; const client = new Client({ host: '127.0.0.1', port: 5432, user: 'postgres', password: 'xxxxxxxxxx', database: 'Luxe-Hotel' }); client.connect() .then(() => console.log('Connected via pg client')) .catch(err => console.error('pg client connection error:', err)); - 检查系统hosts文件:Windows路径为
C:\Windows\System32\drivers\etc\hosts,Linux/macOS路径为/etc/hosts,确保127.0.0.1 localhost条目存在,可暂时注释IPv6的::1 localhost条目测试连接。
内容的提问来源于stack exchange,提问作者Jibril Abshir
相关产品推荐
相关产品推荐

