将节点js连接到heroku上的postgresql

时间:2016-08-31 20:23:30

标签: node.js postgresql heroku

我已经在heroku上部署了我的应用程序,并且能够通过复制和粘贴heroku提供的代码从终端中的pg:psql建立数据库连接。现在我想直接将我的节点应用程序连接到heroku上的postgres但没有成功。我按照关于如何在这里将nodejs连接到postgres的关于heroku的说明.. 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。我如何以及在何处更改它?我输了。我真的很感激,如果我能得到一些帮助来解决它。

1 个答案:

答案 0 :(得分:0)

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

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

由于未设置DATABASE_URL env变量,因此默认为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
相关问题