无法连接Supabase数据库:getaddrinfo ENOTFOUND错误求助
解决连接Supabase数据库时的getaddrinfo ENOTFOUND错误
问题描述
使用pgAdmin和pg库连接Supabase数据库时,一发起连接就收到错误:Error: getaddrinfo ENOTFOUND aws-0-ap-south-1.pooler.supabase.com
同时接口调用时会出现404和上述ENOTFOUND错误。
相关代码
pgconfig.cjs
//pgconfig.cjs const { Pool } = require("pg"); const fs = require("fs"); require("dotenv").config(); const pool = new Pool({ host: "aws-0-ap-south-1.pooler.supabase.com", port: 5432, database: "postgres", user: "postgres.ilquqvtggidzmibcpoze", password: "******", //无特殊字符或数字 }); try { pool.connect(); console.log("Connected to the database."); } catch (error) { console.error("Error connecting to the database:", error.message); } module.exports = pool;
dbroutes.js
//dbroutes.js import express from "express"; import pool from "../config/pgConfig.cjs"; const router = express.Router(); router.post("/newUser", async (req, res, next) => { try { const { email, password } = req.body; // 直接解构 console.log("email:", email, "password:", password); const query = "INSERT INTO testes (email, password) VALUES ($1, $2) RETURNING *"; const values = [email, password]; const result = await pool.query(query, values); console.log("Success in newUser"); res.json(result.rows); // 向前端返回响应 } catch (err) { console.log("error in regNewUser", err); next(err); } }); router.get("/checkDatabase", async (req, res, next) => { try { const query = "SELECT 'Database is working' AS status"; const result = await pool.query(query); res.json(result.rows); } catch (err) { console.log("Error checking database:", err); next(err); } });
错误日志截图

解决方案
排查DNS解析问题
这个错误本质是域名aws-0-ap-south-1.pooler.supabase.com无法被DNS解析。打开终端执行以下命令测试:nslookup aws-0-ap-south-1.pooler.supabase.com # 或者 ping aws-0-ap-south-1.pooler.supabase.com如果无法解析,尝试切换公共DNS(比如8.8.8.8或1.1.1.1),或者检查本地防火墙、代理是否拦截了域名解析请求。
核对Supabase连接信息
登录Supabase控制台,进入对应项目的「设置」->「数据库」,找到连接池区域的Host地址,确认和代码中host字段完全一致;同时检查用户名格式(Supabase用户名是postgres.xxx格式)是否拼写正确。检查网络环境
公司、学校等受限网络可能会屏蔽Supabase的域名,尝试切换到个人热点或其他开放网络测试连接是否正常。修复代码中的异步连接逻辑
当前代码用同步try/catch捕获异步的pool.connect()错误,无法生效。修改为异步写法:// 修改pgconfig.cjs的连接部分 (async () => { try { await pool.connect(); console.log("Connected to the database."); } catch (error) { console.error("Error connecting to the database:", error.message); } })();添加SSL配置
Supabase连接池默认要求SSL连接,在Pool配置中添加SSL参数(开发环境临时使用,生产环境建议配置合法SSL证书):const pool = new Pool({ host: "aws-0-ap-south-1.pooler.supabase.com", port: 5432, database: "postgres", user: "postgres.ilquqvtggidzmibcpoze", password: "******", ssl: { rejectUnauthorized: false } });
内容的提问来源于stack exchange,提问作者Kartic Joshi
相关产品推荐
相关产品推荐

