javascriptnode.jspostgresqlexpressnode-postgres

Node.js - PostgreSQL (pg) : Client has already been connected. You cannot reuse a client


I am just trying to write simple register/login system. I am trying to find if username exists. Here is the steps :

  1. Go localhost:3000/users/register page
  2. Fill in all fields and click register button
  3. Checking my command line if username exists it should print it with console.log

Everything works fine until now.

When I go back to the register page, I fill in all fields again and click register button. Then it throws it in command line :

Error: Client has already been connected. You cannot reuse a client.
at Client._connect (C:\Users\Hasan\Desktop\Projeler\node-ogreniyorum\node_modules\pg\lib\client.js:91:17)
at C:\Users\Hasan\Desktop\Projeler\node-ogreniyorum\node_modules\pg\lib\client.js:310:10
at new Promise (<anonymous>)
at Client.connect (C:\Users\Hasan\Desktop\Projeler\node-ogreniyorum\node_modules\pg\lib\client.js:309:10)
at Object.module.exports.findUserById (C:\Users\Hasan\Desktop\Projeler\node-ogreniyorum\database\register_sql.js:8:22)
at C:\Users\Hasan\Desktop\Projeler\node-ogreniyorum\routes\users.js:37:29
at Layer.handle [as handle_request] (C:\Users\Hasan\Desktop\Projeler\node-ogreniyorum\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Hasan\Desktop\Projeler\node-ogreniyorum\node_modules\express\lib\router\route.js:137:13)
at next (C:\Users\Hasan\Desktop\Projeler\node-ogreniyorum\node_modules\express\lib\router\route.js:131:14)
at Route.dispatch (C:\Users\Hasan\Desktop\Projeler\node-ogreniyorum\node_modules\express\lib\router\route.js:112:3)  

I dont understand because I already end my client after I call my method.

register_sql.js :


module.exports.findUserById =(async (username) =>{
    try {
        await client.connect();
        console.log('Connected successfuly');
        const result = await client.query("select * from users where username = ($1)", [username]);
        console.log(result.rows[0]['username']);
        await client.end();
        console.log('Client disconnected...');
    } catch (err) {
        console.log(err);
    }
});

I call register_sql.js in users.js. Here is users.js :

const router = express.Router();
const registerSQL = require('../database/register_sql');
router.route('/register')
    .get((req, res, next) => {
        res.render('register');
    })
    .post((req, res, next) => {
            const {
                username,
                password,
                password2
            } = req.body;
            let errors = [];
            if (!username || !password || !password2) {
                errors.push("Please fill in all fields!");
            }
            if (password != password2) {
                errors.push("Passwords do not match!");
            }
            if (password.length < 6) {
                errors.push("Password has to be at least 6 characters!");
            }
            if (errors.length > 0) {
                res.render('register', {
                    errors
                });
            } else {
                registerSQL.findUserById(username);
                res.redirect('/');
            }
});

module.exports = router;  

Thank you for helping!


Solution

  • With node-postgres (which is the one you're using) I've only made it work using the pool do manage the connections.

    const pg = require('pg')
    const pool = new pg.Pool();
    
    pool.connect(function(err, client, done) {
        if(err) {
          return console.error('connexion error', err);
        }
        client.query("select * from users where username = ($1)", [username], function(err, result) {
          // call `done()` to release the client back to the pool
          done();
      
          if(err) {
            return console.error('error running query', err);
          }
          console.log(result.rows[0]['username'])
        });
    });