NestJS [TypeOrmModule] 无法连接数据库

时间:2021-02-07 09:49:07

标签: postgresql nestjs typeorm

我想连接到远程 PostgreSQL 数据库(托管在 Heroku 上)并收到此错误:

error: no pg_hba.conf entry for host "<My public IP address>", user "<username>", database "<dbname>", SSL off

这是我的app.module.ts

import { Module } from '@nestjs/common';
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';

const cfg: TypeOrmModuleOptions = {
  type: 'postgres',
  host: process.env.DB_HOST,
  database: process.env.DB_NAME,
  username: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  port: Number(process.env.DB_PORT),
};

@Module({
  imports: [TypeOrmModule.forRoot(cfg)],
})
export class AppModule {}

每个 DB_* 变量都与 Heroku 的 Database Credentials 中的相应值相匹配

我认为问题出在 TypeORM 中,因为连接到具有相同 .env 文件值的同一个数据库在我的其他应用程序(用不同的编程语言编写)中起作用

有什么可能出问题的想法吗?

2 个答案:

答案 0 :(得分:1)

为了解决这个问题,我必须在我的 cfg 对象中添加这些行:

ssl: true,
extra: {
  ssl: {
    rejectUnauthorized: false,
  },
},

使用 ssl: true 选项,我们将不得不使用 SSL 证书,而我们还没有。

理想的解决方案是获取新的 SSL 证书,但对于开发来说,这应该足够了。

答案 1 :(得分:1)

我遇到了同样的错误,并且看起来与您的开发环境相同。

就我而言,我解决了此 Heloku Postgres Connecting in Node.js

中的错误

我选择了另一种方式来省略 ssl 配置,如链接所述。

在项目路径的控制台上,键入以下命令。

<块引用>

heroku 配置:设置 PGSSLMODE=no-verify

以上命令与此相同。 enter image description here