node.js - 节点和 node-postgres 的 Heroku/Postgres“ClientAuthentication”错误
问题描述
我正处于使用 Postgres 在 Heroku 上设置开发应用程序的早期阶段。NodeJS 中问题代码的一个简单版本是:
const {Client} = require('pg');
const client = new Client({connectionString: 'postgres://{username}:{password}@{host}:5432/{dbname}'});
client.connect();
const result = client.query('SELECT now()');
client.end();
connectionString
作为从 data.heroku.com 的凭据窗格提供的字符串的副本,经过检查和重新检查。我可以:
- 使用来自多个不同本地应用程序(例如,DataGrip)的连接字符串进行连接
- 使用该代码(使用不同的连接字符串)连接到在 Docker 映像中运行的本地版本的 Postgres
我不能:
- 从我本地机器上的 Node 应用程序连接
- 从部署到 Heroku 的 Node 应用程序连接
当代码对远程数据库失败时,node-postgres 会抛出此错误:
{
"length": 168,
"name": "error",
"severity": "FATAL",
"code": "28000",
"file": "auth.c",
"line": "496",
"routine": "ClientAuthentication"
}
使用 Node v14.15.1,node-postgres ("pg") 8.5.1
更新: 可能还值得一提的是,我无法从 Java 中找到使此连接失败的方法……故障肯定在 Node <-> node-postgres <-> [基础 postgres 驱动程序] <-> Heroku 中的某个地方(即,数据库很好,连接很好)......但是在哪里?
解决方案
在 Heroku 支持的帮助下,我能够找到基于https://help.heroku.com/MDM23G46/why-am-i-getting-an-error-when-i-upgrade-to-pg-的解决方案8 . “解决方案 1”对我没有任何改变,但“解决方案 2”(使用pg-connection-string
)确实有效。
值得一提的是,我还使用基于 NODE_ENV 环境变量的条件包装 SSL,这样代码既可以与 Heroku Postgres 实例一起使用,也可以与同一个数据库的本地开发版本一起使用。IE:
// centralizing the logic for this so the 'useLocalDb' can be reused
// in multiple functions in the module (in case the logic needs to change
// later, among other reasons)
const useLocalDb = process.env.USE_LOCAL_DB;
// a short version of the working connection code
const {Pool} = require('pg');
const {parse} = require('pg-connection-string')
const config = parse(process.env.DATABASE_URL)
if (!useLocalDb) {
config.ssl = {
rejectUnauthorized: false
}
}
const pool = new Pool(config);
推荐阅读
- scala - 如何参数化将数据帧写入配置单元表
- google-apps-script - 当特定单元格具有特定编号时运行谷歌脚本
- azure-devops-extensions - 有没有办法在不将 doneMatch 添加到字段中的情况下合并字段?
- c# - ViewModel 列表中 DateTime 的良好做法和使用
- excel - 如何单击一个更改每次登录的href?
- windows - 使用 EnableDelayedExpansion 在 FOR 循环中计数
- docusignapi - DocuSign - 查看表单数据
- python - Yfinance - 无法获取最近的股票数据
- unity3d - unity WheelCollider 居中时移动方向错误
- fonts - 如何将蒙特利尔常规浅色字体添加到我的 Shopify 主题