node server can't connect to postgres db

2019-04-28 10:29发布

I recently switched from MySQL to postgres as my database for an node.js project. While I'm able to reach my remote postgres database from my local pgAdmin III (OSX) client, so far I've been unable to connect to my database through node.js. I'm sure that the credentials I entered for pgAdmin and my node.js were exactly the same. The other thing I've tried was setting my local ipadress to trust in stead of md5 in the pg_hba.conf at my database server. Is there anything I did wrong? My favourite search engine came up with some worrying hits about resetting my local os. I just used the example from the github repo doc of node-postgres:

var pg = require('pg');

var conString = "postgres://myusername:mypassword@hostname:5432/dbname";

var client = new pg.Client(conString);
client.connect(function(err) {
  if(err) {
    return console.error('could not connect to postgres', err);
  }
  client.query('SELECT NOW() AS "theTime"', function(err, result) {
    if(err) {
      return console.error('error running query', err);
    }
    console.log(result.rows[0].theTime);
    client.end();
  });
});

And these are the errors I get every time I try to start my server:

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

Help would be greatly appreciated

2条回答
forever°为你锁心
2楼-- · 2019-04-28 11:00

It appears that node-postgres doesn't accept a hashtag in your password. After removing the hashtag I was able to connect without a problem. Wouldn't have thought of that and it didn't strike me as a problem since pgAdmin accepted it.

查看更多
冷血范
3楼-- · 2019-04-28 11:11

The interface in node.js that I used can be found here https://github.com/brianc/node-postgres

var pg = require('pg');
var conString = "postgres://YourUserName:YourPassword@localhost:5432/YourDatabase";

try changing pg:// to postgres://

This was scraped from another stackoverflow article: How to make connection to Postgres via Node.js

查看更多
登录 后发表回答