首页 > 解决方案 > 节点和 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 的凭据窗格提供的字符串的副本,经过检查和重新检查。我可以:

我不能:

当代码对远程数据库失败时,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 中的某个地方(即,数据库很好,连接很好)......但是在哪里?

标签: node.jspostgresqlherokuheroku-postgresnode-postgres

解决方案


在 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);


推荐阅读