Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node-postgres get error connect ECONNREFUSED

I want to connect my apps nodejs using node-posgres to PostgreSQL. My apps in localhost (ubuntu) and my postgresql in virtual machine in the cloud with operating system OpenSuse. This is my code :

var express = require('express');
var app = express();


var http = require('http');
var pg = require('pg');

var conString = "postgres://postgres:[email protected]:5432/postgres";


app.get('/', function (req, res) {
    res.send('HOLAAAA');
});

// respond with "SERVER" on the homepage
app.get('/server', function (req, res) {

    var client = new pg.Client(conString);
    client.connect(function (err) {
        if (err) {
            return console.error('could not connect to postgres', err);
        }
        console.log('CONNECT PASSED');
        client.query('SELECT * FROM visit', function (err, result) {
            if (err) {
                return console.error('error running query', err);
            }
            console.log('QUERY PASSED');
            console.log(result.rows[0].theTime);
            //output: Tue Jan 15 2013 19:12:47 GMT-600 (CST)
            client.end();
        });
    });

});


var server = app.listen(3000, function () {

    var host = server.address().address;
    var port = server.address().port;

    console.log('Example app listening at http://%s:%s', host, port);

});

But i got an error like this:

could not connect to postgres { [Error: connect ECONNREFUSED]
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect' }

Please help me how to solve this. Thanks!

like image 401
zaldysyah Avatar asked Apr 18 '15 02:04

zaldysyah


1 Answers

@Madhavan Kumar thank you very much for your help

the steps to resolve this were as follows:

On the remote server:-

1- find \ -name "postgresql.conf" to find place of config file

2- sudo nano /path/to/config/postgresql.conf to edit config file

3- change this #listen_addresses = 'localhost' to this listen_addresses = '*' then save and exit

4- find \ -name "pg_hba.conf" to find hba config file

5- sudo nano /path/to/config/pg_hba.conf to edit hba config file

6- add host all all 0.0.0.0/0 md5 host all all ::/0 md5

at the end of the file, then save and exit

7- run /etc/init.d/postgresql restart to restart postgres

In the code connect like this:-

let sequelize = new Sequelize(
  config.db.name,
  config.db.username,
  config.db.password,
  {
    host: config.ip,
    port: config.port,
    dialect : 'postgres'
  }
)
like image 162
Ahmad Mayo Avatar answered Sep 18 '22 15:09

Ahmad Mayo