【问题标题】:connecting node js to postgresql on heroku在heroku上将节点js连接到postgresql
【发布时间】:2018-01-04 23:54:30
【问题描述】:

我已经在 heroku 上部署了我的应用程序,并且能够通过复制和粘贴 heroku 提供的代码从终端中的 pg:psql 连接到数据库。现在我想直接将我的节点应用程序连接到 heroku 上的 postgres,但没有成功。我按照 heroku 上的说明将 nodejs 连接到 postgres here.. https://devcenter.heroku.com/articles/heroku-postgresql#connecting-in-node-js 但我似乎无法让它工作。我只是安装了 pg 模块并将 heroku 提供的代码块粘贴到我的 server.js 文件中的 get 请求中。

app.use(express.static('public'));
app.use(bodyParser.json());

app.get('/food', function(req, res) {
    pg.defaults.ssl = true;
    pg.connect(process.env.DATABASE_URL, function(err, client) {
        if (err) throw err;
        console.log('Connected to postgres! Getting schemas...');
        client.query('SELECT table_schema,table_name FROM information_schema.tables;').on('row', function(row) {
        console.log(JSON.stringify(row));
        });
    });
});

http.listen(process.env.PORT || 3000, function(){
    console.log('listening to port 3000!');
});

我从 heroku 日志中得到的错误是..

/appserver.js:53
if (err) throw err;

Error: connect ECONNREFUSED 127.0.0.0.1:5432 

在搜索该错误消息后,我收到一些人建议修复或更改 DATABASE_URL。我如何以及在哪里更改它?我迷路了。如果我能得到一些帮助来解决它,我将不胜感激。

【问题讨论】:

    标签: node.js postgresql heroku


    【解决方案1】:

    pg 连接正在使用您环境中的数据库 url:

    pg.connect(process.env.DATABASE_URL, function(err, client) {}
    

    由于未设置 DATABASE_URL 环境变量,它默认为 localhost 127.0.0.0.1:5432。您可以在 bashrc or bash_profile 中设置 DATABASE_URL。如果您有多个应用程序,您可以更具体地将其命名为 PROJECTNAME_DATABASE_URL。在 Heroku 上,你可以这样设置:

    $ heroku config:set DATABASE_URL=postgres://user:password@host:port/database
    

    【讨论】:

      猜你喜欢
      • 2022-01-10
      • 2013-01-04
      • 1970-01-01
      • 2012-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-07
      • 2018-10-16
      相关资源
      最近更新 更多