'Node.js Postgresql problem querying database using 'pg' module

I'm trying to insert data into a 'users' table inside a postgresql database using the 'pg' NPM module.

But when I make a POST request, the transaction executes indefinitely without terminating and with no response.

I can't seem to locate where the problem is?

I've checked the database settings and everything seems fine.

Could you please help me spot where the problem is with the code?

Thanks in advance!

index.js (main server):


const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
const db = require('./queries')

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({
    extended: true,
}));

app.post('/users', db.createUser);

app.listen(port, () => {
  console.log(`App running on port ${port}.`)
});

queries.js (Script for querying the database):


const Pool = require('pg').Pool;

const pool = new Pool({
    host: 'localhost',
    user: 'travel',
    password: '12345',
    database: 'try',
    port:5432,
});

const createUser = (request, response) => {
    const { name, email } = request.body
  
    pool.query('INSERT INTO users (name, email) VALUES ($1, $2)', [name, email], (error, results) => {
      if (error) {
        throw error
      }
      response.status(201).send(`User added with ID: ${result.insertId}`)
    })
}

module.exports = {
    createUser,
}

Database query for creating 'users' table:


CREATE TABLE IF NOT EXISTS users 
(
    id SERIAL PRIMARY KEY NOT NULL,
    email varchar(255) NOT NULL,
    name varchar(255) NOT NULL
);


Solution 1:[1]

at first when you want to use database you must be connect to database

const { Client } = require("pg")

const config = require("../config")

const client = new Client(config.databse)

client.connect()

module.exports = client

and in your client and pg are almost similar

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Moein T