Heroku 无法连接 Postgres DB/Knex/Express

Heroku can't connect with Postgres DB/Knex/Express

我有一个 Express API 部署到 Heroku,但是当我尝试 运行 迁移时,它抛出以下错误:

heroku run knex migrate:latest Running knex migrate:latest on ⬢ bookmarks-node-api... up, run.9925 (Free) Using environment: production Error: connect ECONNREFUSED 127.0.0.1:5432 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1117:14)

在我的 knexfile.js 中,我有:

production: {
    client: 'postgresql',
    connection: {
      database: process.env.DATABASE_URL
    },
    pool: {
      min: 2,
      max: 10
    },
    migrations: {
      directory: './database/migrations'
    }
  }

我还尝试将迁移目录分配给 tableName: 'knex_migrations',这会引发错误:

heroku run knex migrate:latest Running knex migrate:latest on ⬢ bookmarks-node-api... up, run.7739 (Free) Using environment: production Error: ENOENT: no such file or directory, scandir '/app/migrations'

这是在 Heroku 中设置的配置:

-node-api git:(master) heroku pg:info
=== DATABASE_URL
Plan:                  Hobby-dev
Status:                Available
Connections:           0/20
PG Version:            10.7
Created:               2019-02-21 12:58 UTC
Data Size:             7.6 MB
Tables:                0
Rows:                  0/10000 (In compliance)
Fork/Follow:           Unsupported
Rollback:              Unsupported

我认为问题是出于某种原因,它正在查看数据库的 localhost,就好像环境被读取为 development 虽然跟踪显示 Using environment: production .

您应该检查是否按照 these docs since the DATABASE_URL is automatically set for you as stated here 中所述设置了 Postgres 附加组件。

当您提供一个对象作为您的 connection 时,您提供的是连接信息的各个部分。在这里,您是说 database 的名称是 process.env.DATABASE_URL:

中包含的所有内容
connection: {
  database: process.env.DATABASE_URL
},

您未提供值的任何键都将回退到默认值。例如 host 键,默认为本地计算机。

但是 DATABASE_URL 环境变量在单个文件中包含 所有 您需要连接的信息(主机、端口、用户、密码和数据库名称)细绳。 That whole value should be your connection setting:

connection: process.env.DATABASE_URL,