Cannot connect local PostgreSQL DB in Nodejs

Viewed 2276

I connect my PostgreSQL local database in Node.js server using pg.

All worked fine, but suddenly it stopped to work.

This is my code:

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;

Here I call it:

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

It stuck on pool.query. 'before connection' is logged, no error is thrown.

The very same code works fine with my remote db, and I can connect the local db with pgAdmin.

2 Answers

I found my problem in node version - some days ago I updated it to 14.5.0.

revise it to 12.18.2 LTS solve the problem.

Related