【问题标题】:Heroku PostgreSQL connections aren't being terminated for certain Express routes某些 Express 路由不会终止 Heroku PostgreSQL 连接
【发布时间】:2020-11-03 02:59:50
【问题描述】:

我有 2 条路由在下面查询我的 Heroku postgres 数据库:

app.post('/signin', (req,res) => {
    let client = new Client({
        connectionString: process.env.DATABASE_URL,
        ssl: {
          rejectUnauthorized: false
        }
      });
    client.connect()
        .then(()=>client.query(`SELECT * FROM users WHERE username = '${req.body.user}';`)) 
        .then((results) => {
            if(results.rowCount===1){ 
                bcrypt.hash(req.body.pass, saltRounds, function(err, hash) {
                    if(bcrypt.compareSync(req.body.pass, results.rows[0].password)){
                        res.json('loggedIn') //User and pass are good
                    } else{
                        res.json('wrongPw') //Pass is wrong
                    }
                })
            } else{
                res.json('user not found') //User dne
            }
        })
        .catch(err=>console.log(err))
        .finally(()=>client.end())
})

app.post('/signup', (req,res) => {
    let client = new Client({
        connectionString: process.env.DATABASE_URL,
        ssl: {
          rejectUnauthorized: false
        }
      });
    bcrypt.hash(req.body.pass, saltRounds, function(err, hash) {
        // Store hash in password DB.
        client.connect()
            .then(()=> client.query(`INSERT INTO users (username, password) VALUES ('${req.body.user}', '${hash}')`))
                .then(results => res.json(results))
                .catch(err=>res.json('user already exists'))

        .catch(err=>console.log(err))
        .finally(() => client.end())
    });
});


每当我使用它们时,我都会注意到它们与数据库的连接仍然存在。执行登录和注册后,我仍然看到这个。

我等着看他们是否会超时,但他们从来没有这样做过,最终不得不使用 pg:killall,我希望以后避免这种情况。

【问题讨论】:

  • 首先,我建议您使用连接池,而不是每次向数据库发出请求时打开和关闭新连接。与使用线程池并保持连接打开相比,创建连接的行为非常耗费资源。其次,当它失败时,您没有处理 bcrypt 函数承诺链。你的 .catch() 和 .finally() 调用应该在 }); 行之后,因为这就是关闭你的 bcrypt 函数调用

标签: node.js postgresql express heroku node-postgres


【解决方案1】:

已修复,在登录/注册后使用的另一条路线并未结束。我结束了另一条路线,现在没有连接

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-01
    • 2012-06-18
    • 1970-01-01
    • 2014-06-08
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    相关资源
    最近更新 更多