Node.js - PostgreSQL(pg):客户端已连接,您不能重用客户端

sxissh06  于 12个月前  发布在  PostgreSQL
关注(0)|答案(6)|浏览(202)

我只是想写简单的注册/登录系统.我试图找到如果用户名存在.这里是步骤:
1.转到localhost:3000/users/register页面
1.填写所有字段并点击注册按钮
1.检查我的命令行,如果用户名存在,它应该打印它与console.log

直到现在一切都很好

当我回到注册页面时,我再次填写所有字段并单击注册按钮。然后它将其抛出命令行:

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)

字符串
我不明白,因为我已经结束我的客户端后,我调用我的方法。

  • 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);
    }
});


我在users.js中调用register_sql.js。这里是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;


谢谢你的帮助!

thtygnil

thtygnil1#

使用node-postgres(这是您正在使用的),我只使用池来管理连接。

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'])
    });
});

字符串

vmjh9lq9

vmjh9lq92#

我也遇到了同样的问题,不要在函数外创建新的客户端。

- const client = new pg.Client(connection);
-
 function test() {
+    const client = new pg.Client(connection);
+
     client.connect(err => {
         if (err) {
             console.log(err);
             return;
         }
         client.query('select 123', [], (err, data) => {
             if (err) {
                 console.log(err);
             } else {
                 console.log('DATA:', data.rows[0]);
             }
             client.end();
         });
     });
 }

字符串

kgsdhlau

kgsdhlau3#

我设法在不使用pool的情况下解决了这个问题。也许这不是最正确的解决方案,但它有效。首先创建一个单独的js文件,在其中连接客户端并导出它:

const pg = require('pg')
const client = new pg.Client('your connection string')
client.connect()
module.exports = client

字符串
然后你就可以使用导出的客户端了,它已经连接好了,所以它不会在每次请求时重新连接。一定要从你连接它的js文件中导入客户端。

const client = require('../db')
    const register = async (req, res) => {
        const {email, password, username} = req.body
        const hashedPassword = await bcrypt.hash(password, 10)
        const command = `insert into users(email, username, password, created) VALUES ('${email}', '${username}', '${hashedPassword}', current_timestamp)`
        await client.query(command, (err, result) => {
err ? res.json({error: err.detail}) : res.json({message: 'User created!'})
})
    }

kninwzqo

kninwzqo4#

好了,问题发生了,因为你还没有关闭连接到数据库.记住,你必须关闭连接之前,你发送的东西给客户端这样:

try {
  await client.connect();
  const result = await client.query(query, values);
  await client.end();
  res.status(201).send({
    result,
  });
} catch (err) {
  return res.send({
    error: err.detail,
      message: "Can't create a new user, please check your info again!",
    });
  }

字符串

7bsow1i6

7bsow1i65#

方法是更好的做法,但如果有人想与客户端方法连接,那么这个解决方案将工作。

代码将与客户端的方法:

client.connect();

client.query(`select * from users where username = ($1)`, (err, result)=>{
  try{
          console.log("Test", result)
           res.send(result)
        } catch{
          console.log("err", err)
          res.status(500).json(err);
    
        }

    client.end();

字符串
})

hi3rlvi2

hi3rlvi26#

我正在那样做

export const getConnection = async () => {
   const client = new Client()
 
   await client.connect()
 
   return client
}

字符串
然后

getConnection().query(`...`)

相关问题