Reputation: 91
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!
Upvotes: 9
Views: 36506
Reputation: 1003
@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'
}
)
Upvotes: 8
Reputation:
First try a simple psql command from the local end,
psql -d DBNAME -h YOUR_IP -U USERNAME
it mayn't work for you. This can be because of two reasons, the VM's ip is not resolved by your local station. (or) is the VM in public cloud like amazon (or) your desktop. If it is in public group, the port 5432 on the VM is not open to the public world. You need to write a security group to do it.
If you are sure, it is not any one of the above two issues, better visit postgres /etc/postgresql/9.3/main/pg_hba.conf
and see if remote connections are enabled. NodeJs app, you must test at the end.
Upvotes: 2