skip to Main Content

So I am able to connect to my psql database through the command prompt using the prompt (psql -h localhost -p 5432 -U postgres -d Luxe-Hotel) and putting in the password but I am unable to connect through node.js.

import express from "express";
import cors from "cors";
import pkg from "body-parser";
import bcrypt from "bcrypt";
import knex from "knex";
import handleRegistration from "./controllers/handleRegistration.js";
import handleSignIn from "./controllers/handleSignIn.js";

const db = knex({
    client: 'pg',
    connection: {
        host: 'localhost',
        port: 5432,
        user: 'postgres',
        password: 'xxxxxxxxxx',
        database:'Luxe-Hotel'
    },
    pool: { min: 0, max: 7 }
});

db.raw('SELECT 1')
  .then(() => console.log('PostgreSQL connected'))
  .catch(err => console.error('PostgreSQL connection error:', err));

So when I start the server I get the error:
"

PostgreSQL connection error: AggregateError [ECONNREFUSED]: 
    at internalConnectMultiple (node:net:1122:18)
    at afterConnectMultiple (node:net:1689:7) {
  code: 'ECONNREFUSED',
  [errors]: [
    Error: connect ECONNREFUSED ::1:5432
        at createConnectionError (node:net:1652:14)
        at afterConnectMultiple (node:net:1682:16) {
      errno: -111,
      code: 'ECONNREFUSED',
      syscall: 'connect',
      address: '::1',
      port: 5432
    },
    Error: connect ECONNREFUSED 127.0.0.1:5432
        at createConnectionError (node:net:1652:14)
        at afterConnectMultiple (node:net:1682:16) {
      errno: -111,
      code: 'ECONNREFUSED',
      syscall: 'connect',
      address: '127.0.0.1',
      port: 5432
    }
  ]
}

"
I’ve turned off the firewalls, check the pgsl confiq files for listening address and ports, went over the config settings in my code and still no luck.

2

Answers


  1. Chosen as BEST ANSWER

    Ahh the issue was I was using git codespaces. Once I changed to vs code desktop it connected fine. Thanks guys.


  2. Most likely the problem is that this user can connect from the local network.

    Open postgresql.conf file and replace line

    listen_addresses = 'localhost'
    

    with

    listen_addresses = '*'
    

    Open pg_hba.conf and add following entry at the very end.

    host all all 0.0.0.0.0/0 md5
    host all all ::/0 md5
    

    Or you can replace 0.0.0.0.0/0 with your IP address.

    After that you will be able to connect using Node.JS

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search