【问题标题】:Why is node-postgres (pg) hanging when I call client.connect()?为什么当我调用 client.connect() 时 node-postgres (pg) 挂起?
【发布时间】:2020-11-02 15:55:54
【问题描述】:

我最近不得不将我的 vue.js 应用程序(后端的 node.js)的 node.js 版本从 v13.5.0 升级到 v14.5.0。我重新安装了所有节点包,升级了我必须升级的那些,现在应用程序挂起所有数据库调用。我们使用 pg (node-postgres) 进行数据库调用。我将 pg 升级到 7.18.2 版本。

我们的初始化代码如下所示:

constructor() {
  this.pg = require('pg');
  this.client = null;
  this.initPromise = null;
}

async init() {
  if (!this.initPromise) {
    this.client = new this.pg.Client({
      application_name: 'Back end',
      ssl: {
        rejectUnauthorized: false
      }
    });
    this.initPromise = this.client.connect();
  }
  return this.initPromise;
}

async query(query, params) {
  await this.init();
  return await this.client.query(query, params);
}

我在 this.init() 调用周围放置控制台日志,如下所示:

console.log('before');
await this.init();
console.log('after');

'after' 永远不会打印出来。

有谁知道我升级节点版本后为什么会挂起?

【问题讨论】:

  • init 方法不应该是async,因为您没有在其中使用await,但这与问题无关
  • 您在哪里将连接详细信息和凭据传递给客户端?
  • 您之前安装了哪个版本的 node-postgres?
  • 根据 node-postgres 文档 (node-postgres.com/features/connecting),它从环境变量中获取连接详细信息。但是我尝试将它们显式传递给 Client 构造函数: this.client = new this.pg.Client({host: ..., database: ..., etc.});但无济于事。我之前安装了 7.8.0。

标签: node.js postgresql freeze node-postgres


【解决方案1】:

pg v.8.3.0 似乎解决了这个问题。我通过运行 npm install pg 获得了 v7.18.2。似乎并不总是安装最新版本。 npm install pg@latest 可以解决问题。

【讨论】:

  • 遇到了同样的问题,花了 2 个小时试图解决这个问题。可以确认更新到最新版本修复它。
  • 根本原因是节点 14 引入了破坏 pg 的更改。升级 pg 解决它。我花了很长时间试图理解为什么简单的 postgres 代码在 dev 中不起作用,但在使用节点 12 的 prod 中却很好。更多信息:stackoverflow.com/questions/61611039/…
  • 我正要失去理智,直到我偶然发现了这一点。谢谢!
【解决方案2】:

@gib65 升级到 v.8.3.0 对我来说也是一个诀窍,就是在等待和异步上敲我的脑袋。还以为我又是n00b了……

【讨论】:

  • 嗨疯子,我想最好添加评论来回复评论。您的评论似乎不是问题的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-22
  • 2022-12-16
  • 1970-01-01
  • 1970-01-01
  • 2014-12-20
  • 1970-01-01
  • 2011-11-05
相关资源
最近更新 更多