Node.js由于某种原因无法连接到postgresql

代码在创build查询对象时崩溃。

var conString = "postgres://mydbusr:thepassword@localhost/mydb"; var client = new pg.Client(conString); client.connect(function(err) { if (err) { return console.error('could not connect to postgres', err); } var query = client.query('SELECT id FROM people'); //THE PROBLEM IS HERE query.on('row', function(row) { //Do something }); client.end(); }); 

这是我真的不明白的错误:

 events.js:72 throw er; // Unhandled 'error' event ^ Error: Connection terminated at null.<anonymous> (/liveupdates/node_modules/pg/lib/client.js:184:29) at g (events.js:180:16) at EventEmitter.emit (events.js:92:17) at Socket.<anonymous> (/liveupdates/node_modules/pg/lib/connection.js:66:10) at Socket.EventEmitter.emit (events.js:95:17) at TCP.close (net.js:466:12) 

你忘了,几乎所有对数据库的调用都是asynchronous的。

在你的代码中,你使用closures了连接

 client.end(); 

没有等待,所有查询和相应的答复已经处理。

我同意Sirko,把query.eon client.end()放在query.on() ,满足所有行都从数据库中获取的条件。

此外,删除处理错误的块中的return语句。 一般来说,大多数数据库客户端尝试多次连接数据库遇到错误时。 如果您在第一次遇到错误时返回,您的客户甚至不会再尝试第二次。