node-postgres:[error]此套接字已由另一方

时间:2017-09-14 09:33:04

标签: javascript node.js postgresql node-postgres

我使用node-protgres来操作我的nodejs应用程序中的数据库。

我做了什么:

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 

            });
    });

}

该功能运行正常,但服务器不断向我发送错误报告确定为严重。我检查了日志:

  

空闲客户端错误此套接字已被另一方结束错误:   此套接字已由另一方结束       在Socket.writeAfterFIN [as write](net.js:291:12)       在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)       在Client.end(/var/app/current/node_modules/pg/lib/client.js:409:12)       在Pool._remove(/var/app/current/node_modules/pg-pool/index.js:135:12)       在Timeout.setTimeout(/var/app/current/node_modules/pg-pool/index.js:38:12)       在ontimeout(timers.js:365:14)       在tryOnTimeout(timers.js:237:5)       在Timer.listOnTimeout(timers.js:207:5)

我认为问题来自' done()'没有工作或被放错了地方。

任何建议表示赞赏。

2 个答案:

答案 0 :(得分:1)

尝试在回调内部声明pool对象。我在使用postgres客户端时遇到了类似的错误。我通过在GET请求的回调中声明client来解决了这个问题。

看看这个问题,这是我找到解决方案的地方:Github issue

答案 1 :(得分:0)

希望这可以帮助你=)。我想您可以使用此链接修复http://mherman.org/blog/2015/02/12/postgresql-and-nodejs/#.WbpNjMgjGHs