AWS Lambda Node.js 使用 Pool 连接 PostgreSQL 时报错
Lambda PostgreSQL Node.js About 3,067 words错误信息
如果不指定SSL会得到以下错误
{
"errorType": "error",
"errorMessage": "no pg_hba.conf entry for host \"127.0.0.1\", user \"postgres\", database \"postgres\", no encryption",
"code": "28000",
"length": 160,
"name": "error",
"severity": "FATAL",
"file": "auth.c",
"line": "543",
"routine": "ClientAuthentication",
"stack": [
"error: no pg_hba.conf entry for host \"127.0.0.1\", user \"postgres\", database \"postgres\", no encryption",
" at /var/task/index.js:9:15227",
" at process.processTicksAndRejections (node:internal/process/task_queues:104:5)",
" at async BufferedInvokeProcessor.KK [as handler] (/var/task/index.js:67:39303)",
" at async BufferedInvokeProcessor.processInvoke (file:///var/runtime/index.mjs:1092:22)",
" at async _Runtime.processSingleConcurrent (file:///var/runtime/index.mjs:1178:7)",
" at async _Runtime.start (file:///var/runtime/index.mjs:1165:7)",
" at async ignition (file:///var/runtime/index.mjs:1634:5)"
]
}
如果改成?sslmode=required会得到以下错误
{
"errorType": "Error",
"errorMessage": "self-signed certificate in certificate chain",
"code": "SELF_SIGNED_CERT_IN_CHAIN",
"stack": [
"Error: self-signed certificate in certificate chain",
" at /var/task/index.js:9:15227",
" at process.processTicksAndRejections (node:internal/process/task_queues:104:5)",
" at async BufferedInvokeProcessor.KK [as handler] (/var/task/index.js:67:39319)",
" at async BufferedInvokeProcessor.processInvoke (file:///var/runtime/index.mjs:1092:22)",
" at async _Runtime.processSingleConcurrent (file:///var/runtime/index.mjs:1178:7)",
" at async _Runtime.start (file:///var/runtime/index.mjs:1165:7)",
" at async ignition (file:///var/runtime/index.mjs:1634:5)"
]
}
解决方法
配置ssl的rejectUnauthorized为false。
import { Pool } from "pg";
pool = new Pool({
host: config.host,
user: config.username,
password: config.password,
database: config.engine,
port: config.port,
ssl: {
rejectUnauthorized: false
}
});
完整代码
import { Pool } from "pg";
import { SecretsManagerClient, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager";
type DbSecret = {
username: string;
password: string;
host: string;
port: number;
engine: string;
};
const client = new SecretsManagerClient({
region: "us-east-1",
});
let pool: Pool | null = null;
export const getDbClient = async () => {
if (pool) return pool;
const SecretId = process.env.DB_SECRET_ID!;
const res = await client.send(new GetSecretValueCommand({ SecretId }));
const raw = res.SecretString ?? "";
const config = JSON.parse(raw) as DbSecret;
pool = new Pool({
host: config.host,
user: config.username,
password: config.password,
database: config.engine,
port: config.port,
ssl: {
rejectUnauthorized: false
}
});
return pool;
};
Views: 4 · Posted: 2026-07-22
———         Thanks for Reading         ———
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...