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

启动服务器遇SASL密码错误:移除db.connect()即可正常启动

解决PostgreSQL连接错误:SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string

错误原因

这个错误是因为pg库的Client实例调用db.connect()时,尝试使用SCRAM密码认证,但未提供有效密码字符串,而你的本地PostgreSQL实例大概率配置的是信任/peer认证(无需密码),两者认证方式不匹配,导致启动时抛出错误。

移除db.connect()后能正常启动,是因为pg库会在执行第一个数据库查询(比如db.query())时自动发起连接,此时会适配数据库的认证规则,不会触发启动阶段的连接错误。

修复方案

方案1:调整Client配置适配本地认证

如果本地PostgreSQL用的是peer/trust认证,在Client配置里明确指定主机,让连接适配本地认证规则:

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

let DB_URI;

if (process.env.NODE_ENV === "test") {
  DB_URI = "postgresql:///users_test";
} else {
  DB_URI = "postgresql:///users";
}

let db = new Client({
  connectionString: DB_URI,
  host: 'localhost' // 明确指定本地主机,适配peer/trust认证
});

// 可保留连接逻辑并添加错误处理
db.connect(err => {
  if (err) {
    console.error('数据库连接失败:', err.stack);
  } else {
    console.log('数据库连接成功');
  }
});

module.exports = db;

方案2:移除主动连接,让pg自动处理

直接去掉db.connect(),pg会在执行查询时自动建立连接,既不影响功能,也能避免启动时的错误:

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

let DB_URI;

if (process.env.NODE_ENV === "test") {
  DB_URI = "postgresql:///users_test";
} else {
  DB_URI = "postgresql:///users";
}

let db = new Client({
  connectionString: DB_URI
});

// 移除db.connect(),pg会自动在查询时连接
module.exports = db;

方案3:检查PostgreSQL认证配置

打开PostgreSQL的pg_hba.conf文件,确认本地连接的认证方式:

  • 若为local类型连接,确保认证方式是trust或peer,而非scram-sha-256或md5
  • 若需要密码认证,在连接字符串中补充用户名和密码,格式示例:postgresql://your_username:your_password@localhost/users

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 03:35:16