【问题标题】:Cannot connect local PostgreSQL DB in Nodejs无法在 Nodejs 中连接本地 PostgreSQL 数据库
【发布时间】:2020-11-05 04:35:41
【问题描述】:

我使用 pg 在 Node.js 服务器中连接我的 PostgreSQL 本地数据库。

一切正常,但突然停止工作。

这是我的代码:

const {Pool} = require('pg')
const connectionString = process.env.DATABASE_URL;
const ssl = process.env.NODE_ENV == 'production' ? '?ssl=true' : '';
const pool = new Pool({
    connectionString: connectionString + ssl
});

const db = {
    pool: pool,
    test: async () => {
        try {
            console.log('before connection');
            let result = await pool.query('SELECT $1::text as status', ['connected']);
            console.log('connected')
            return result.rows[0].status;
        } catch (error) {
            console.error('Unable to connect to the database:', error);
            return null;
        }
    }
}

module.exports = db;

我称之为:

const express = require('express')
const Router = express.Router();
const db = require('./database')

Router.get('/testdb', async (req, res) => {
    try {
        let result = await db.test();
        res.status(200).send(result);
    } catch (error) {
        res.status(500).send(error);
    }
})

它停留在pool.query。记录“连接前”,不会引发错误。

同样的代码适用于我的远程数据库,我可以使用 pgAdmin 连接本地数据库。

【问题讨论】:

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


    【解决方案1】:

    这是pg 与 node.js 14 版本之间的不兼容问题。另请参阅以下已跟踪和修复的 GitHub 问题:

    tl;dr:将 pg 升级到大于 8.0.3 (pg>=8.0.3) 的版本。

    【讨论】:

      【解决方案2】:

      我在节点版本中发现了我的问题 - 几天前我将其更新为 14.5.0

      修改为12.18.2 LTS解决问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-30
        • 1970-01-01
        • 1970-01-01
        • 2016-03-01
        • 2020-12-12
        • 2021-09-25
        • 2017-11-27
        • 1970-01-01
        相关资源
        最近更新 更多