node-postgres: [error] This socket has been ended by the other party

2.7k views Asked by At

I use node-protgres to manipulate the db in my nodejs app.

What I have done:

const { Pool, Client } = require('pg')
var dbconnect = {
    user: 'xxxxx',
    database: 'xxxxx',
    password: 'xxxxx', 
    host: 'xxxxx.yyyyy.zzzzz.eu-west-1.rds.amazonaws.com',
    port: 0000, 
    max: 20, // max number of clients in the pool
    idleTimeoutMillis: 30000,
    connectionTimeoutMillis: 2000 
};
const pool = new Pool(dbconnect);
pool.on('error', function (err, client) {
    console.error('idle client error', err.message, err.stack)
});

function listOfPets(req, res) {

 pool.connect(function (err, client, done) {
        if (err) {
            return console.error('error fetching client from pool', err);
        }

        var sql =
            "SELECT * FROM pets"
        client.query(sql, function (err, result) {

                done();

                if (err) {
                    return console.error('error running query', err);
                }

                ... //Handle the result 

            });
    });

}

The function is working fine, however the server keep sending me the error report OK to severe. I checked the log:

idle client error This socket has been ended by the other party Error: This socket has been ended by the other party at Socket.writeAfterFIN [as write] (net.js:291:12) at Connection.end (/var/app/current/node_modules/pg/lib/connection.js:313:22) at global.Promise (/var/app/current/node_modules/pg/lib/client.js:410:23) at Client.end (/var/app/current/node_modules/pg/lib/client.js:409:12) at Pool._remove (/var/app/current/node_modules/pg-pool/index.js:135:12) at Timeout.setTimeout (/var/app/current/node_modules/pg-pool/index.js:38:12) at ontimeout (timers.js:365:14) at tryOnTimeout (timers.js:237:5) at Timer.listOnTimeout (timers.js:207:5)

I think the problem came from the 'done()' doesn't work or was put at wrong place.

Any suggestion is appreciated.

2

There are 2 answers

1
xuan hung Nguyen On

Hope this can help you =). I think you can use this link to fixed http://mherman.org/blog/2015/02/12/postgresql-and-nodejs/#.WbpNjMgjGHs

0
Beni Trainor On

Try declaring the pool object inside the callback. I had a similar error with a postgres client. I solved it by declaring the client inside the callback for a GET request.

Have a look at this issue, it's where I found my solution: Github issue