I have deployed my app on heroku and was able to make a connection to the database from pg:psql in my terminal by copying and pasting the code provided by heroku. Now i want to directly connect my node app to postgres on heroku but no success. I followed the instruction on heroku on how to connect nodejs to postgres here.. https://devcenter.heroku.com/articles/heroku-postgresql#connecting-in-node-js but i can't seem to get it to work. I simply installed pg module and pasted the block of code provided by heroku inside my get request in my server.js file.

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!');
});

the error i get from heroku logs is..

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

Error: connect ECONNREFUSED 127.0.0.0.1:5432 

after searching for that error message, i get some people suggesting on fixing or changing the DATABASE_URL. How and where do i change it? I'm lost. I would really appreciated if i can get some help to fix it.

share|improve this question

The pg connection is using the database url in your environment:

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

Because the DATABASE_URL env variable is not set, it defaults to localhost 127.0.0.0.1:5432. You can set DATABASE_URL in your bashrc or bash_profile. You can name it more specifically PROJECTNAME_DATABASE_URL if you have multiple apps. On Heroku, you can set it like this:

$ heroku config:set PROJECTNAME_DATABASE_URL=[database url]
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.