Knex Heroku服务器与Postgres数据库的连接问题-Node.js

时间:2020-06-21 00:44:49

标签: node.js postgresql heroku psql

我试图用GraphQL和Knex运行我的node-express服务器,并将其连接到heroku中的PostgresQL数据库。

当我运行heroku bash CLI并尝试迁移时,出现此错误


    ~ $ npm run migrate

    > syncify-server@0.0.0 migrate /app
    > knex migrate:latest

    Using environment: staging
    Error: connect ECONNREFUSED 127.0.0.1:5432
        at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)
    npm ERR! code ELIFECYCLE
    npm ERR! errno 1
    npm ERR! syncify-server@0.0.0 migrate: `knex migrate:latest`
    npm ERR! Exit status 1
    npm ERR! 
    npm ERR! Failed at the syncify-server@0.0.0 migrate script.
    npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

    npm ERR! A complete log of this run can be found in:
    npm ERR!     /app/.npm/_logs/2020-06-21T00_20_17_455Z-debug.log

它在开发中在本地运行良好。我的knex.js文件


    import dotenv from 'dotenv'
    import knex from 'knex'
    import mockKnex from 'mock-knex'

    dotenv.config()
    let knexConnection

    if (process.env.NODE_ENV === 'test') {
      knexConnection = knex({
        client: 'pg',
        debug: false,
      })
      mockKnex.mock(knexConnection)
     } else {
          knexConnection = knex({
            client: 'pg',
            connection: {
              url: process.env.DATABASE_URL,
              type: 'postgres',
              charset: 'utf8',
              ssl: false
            },
          })
        }

    export default knexConnection


和knexfile.js

require('dotenv').config()

module.exports = {
  development: {
    client: 'pg',
    connection: {
      url: process.env.DATABASE_URL,
      charset: 'utf8',
    },
  },

  staging: {
    client: 'pg',
    connection: {
      url: process.env.DATABASE_URL,
      charset: 'utf8',
    },
    pool: {
      min: 2,
      max: 10,
    },
    migrations: {
      tableName: 'knex_migrations',
    },
  },

  production: {
    client: 'pg',
    connection: {
      url: process.env.DATABASE_URL,
      charset: 'utf8',
    },
    pool: {
      min: 2,
      max: 10,
    },
    migrations: {
      tableName: 'knex_migrations',
    },
  },
}

我一直在试图找出问题所在,但感觉可能不止一个。

在配置变量中,我将DATABASE_URL作为heroku psql db URL,将NODE_ENV作为“ staging”以及所有auth0设置。

我能够在命令行中使用psql访问在线数据库。我有正确的表,可以使用SQL语句创建和检索数据。

当我将本地服务器配置为使用heroku psql db时,出现错误消息 relation "users" does not exist 如果我尝试数据库中的其他表也是如此。

我尝试将SSL更改为true,这会引发错误,将false更改为false,这似乎并没有任何损害。 (我尝试了很多其他事情)

如果我点击了在线heroku服务器,它只会抛出一个通用错误,没有任何详细信息。

源代码here

1 个答案:

答案 0 :(得分:0)

为此损失了几天的时间,我已将其修复。

经典env变量错误。 我没有在配置中包含AUTH0_ISSUER,该配置是在不久前但在首次部署到heroku之后的更新中实现的。

尽管我将knex文件配置为使用DATABASE_URL,但它并没有选择它,仅在使用了所有五个单独设置的情况下才连接到数据库。

DB_NAME=
DB_USER=
DB_PASSWORD=
DB_HOST=
DB_PORT=

我无法弄清楚为什么,但是我在'./dist'中有server.js文件,这些文件在缩小的代码中引用,所以我猜想它必须但已经以某种方式转译为可以使用,并且有点卡住了。 我倾向于使用DATABASE_URL,因为我认为heroku会不时动态地更新此值,并且不确定如何保护服务器。 ?