Error occurred while trying to authenticate the user "root" with the password in Linux using NodeJS, Express, and PostgreSQL

Update -

Hurrah! It appears I neglected to consult the manual. Following the guidelines exactly for the environmental variables seems to be necessary.

Corrected code:

# PostgreSQL Database Information
PGDATABASE_TEST = user_db
PGDATABASE = user_db
PGUSER = postgres
PGPASSWORD = password

# PostgreSQL Host and Port Information
PGHOST = localhost
PGPORT = 5432

--

I am utilizing .env variables to establish a connection with a Postgres Database.

Upon submitting data through Postman to an Express API, I encounter an error message as shown below:

            throw new ErrorHandler(error.statusCode, error.message)
                  ^

ErrorHandler: password authentication failed for user "tito"
    at UserService.createUserAccount (/home/tito/Documents/GitHub/***/server/services/user.service.js:11:19)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async createUserAccount (/home/tito/Documents/GitHub/***/server/controllers/user.controller.js:11:18) {
  status: 'error',
  statusCode: undefined
}

Apparently, it is using my operating system username instead of the one set in the .env file. Running node with sudo results in the authentication error with root.

My db.js:

require("dotenv").config();
const { Pool } = require("pg");

// Determine which Database to use. Live environment is secure.
const isProduction = process.env.NODE_ENV === 'PRODUCTION';
const database = process.env.NODE_ENV === 'TEST' ? process.env.PG_TEST_DATABASE : process.env.PG_DATABASE;

// Construct request to Database
const connectionString = `postgresql://${process.env.PG_USER}:${process.env.PG_PASS}@${process.env.PG_HOST}:${process.env.PG_PORT}/${database}`;

// Initialize Pool
const pool = new Pool ({
    connectionString: isProduction ? process.env.DATABASE_URL : connectionString,
    ssl: isProduction ? { rejectUnauthorized: false } : false
});

console.log(`Ready at : ${connectionString}`)

module.exports = {
    query: (text, params) => pool.query(text, params),
    end: () => pool.end()
}

My .env:

# Express API Port.
PORT = 5000

# Environment - TEST for local, PRODUCTION for live.
NODE_ENV = PRODUCTION

# PostgreSQL Database Information
PG_TEST_DATABASE = user_db
PG_DATABASE = user_db
PG_USER = postgres
PG_PASS = password

# PostgreSQL Host and Port Information
PG_HOST = localhost
PG_PORT = 5432

My UserService:

const {
    createUserAccount_DB
} = require("../db/user.db");
const { ErrorHandler } = require("../helpers/error")

class UserService {
    createUserAccount = async (user) => {
        try {
            return await createUserAccount_DB(user);
        } catch (error) {
            throw new ErrorHandler(error.statusCode, error.message)
        }
    }
}

module.exports = new UserService();

And my createUserAccount:

const userService = require("../services/user.service");
const { ErrorHandler } = require("../helpers/error");

const createUserAccount = async (req, res) => {

    console.log("Create Account API Triggered");

    const { user_name, user_pass, user_email } = req.body;
     
    const user = await userService.createUserAccount({
        user_name,
        user_pass,
        user_email
    });

    res.status(201).json({
        status: "success",
        user,
    })
};

Answer №1

Yay! I finally figured it out by actually reading the manual this time. It turns out that using the environmental variables exactly as specified in the documentation is crucial.

Here's the corrected code:

# Configuration for PostgreSQL Database
DATABASE_NAME = user_db
USERNAME = postgres
PASSWORD = password

# Server Details for PostgreSQL
HOST = localhost
PORT = 5432

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for choosing an option in MUI select list using jest

I am looking for a way to automate tests for a Material UI select component using Jest. Is there a way to select an option from the list of options in the Material UI component and confirm that its value has been successfully populated in Jest? I have se ...

Uploading images using the power of Angular and Node.js

I have been struggling with a persistent issue for quite some time now, and I have not been able to find a solution anywhere. My goal is to allow users to update their avatars on their profiles. However, every time I attempt to pass the file to my node ser ...

two occurrences of the identical controller in AngularJS

Encountering a dilemma (admittedly, not the best approach). There is a single view featuring a split screen; an input field occupies the left side while its corresponding value appears on the right. Both sides are managed by the same controller, using the ...

Exploring the variation between server port and websocket port in a Node.js chat system

I'm currently working on developing a multi-room chat application in node.js that uses socket.io and express. I've been having some confusion regarding the differences between the server port and the websocket port. As far as I know, the server p ...

Having trouble getting sweet alert to work with my PHP script

I’m integrating Sweet Alerts 2 into my webpage in order to prompt the user when trying to delete something. However, I'm encountering an issue where the PHP file is not being triggered when the user presses delete and the Sweet Alert does not appear ...

Styling Process Steps in CSS

Just starting out with CSS! I'm looking to replicate the Process Step design shown in the image. https://i.stack.imgur.com/Cq0jY.png Here's the code I've experimented with so far: .inline-div{ padding: 1rem; border: 0.04rem gray ...

Storing variables in a .env file

Within my project, I currently have an .env file with the following content: NODE_ENV = local PORT = 4220 BASE_URL = "http://198.**.**.**:4220/" PROFILE_UPLOAD = http://198.**.**.**:4220/uploads/profile/ POST_UPLOAD = http://198.**.**.**:4220/uploads/dis ...

Leverage the version attribute within package.json within one of its scripts

Is there a way to access the version attribute of my package.json file within one of its scripts? I want to include the version number in the name of the JS bundle, instead of using a hash as an identifier. This is what I currently have: "build-js": "bro ...

Organizing DIVs upon website initialization

My website features a layout with three columns: <div id="column1"></div> <div id="column2"></div> <div id="column3"></div> I currently have 3 divs on the webpage: <div id="1">aaa</div> <div id="2">b ...

Using NodeJS to convert a Base64 string into a JPEG image with the help of either NodeJS or

I have successfully stored a JPEG image in my MySQL database using the longblob format. Now, when I retrieve the longblob data, I am only getting a base64 string. How can I convert this base64 string back to a readable JPEG image using MySQL or Node.js? B ...

What are some methods to turn off AJAX caching in JavaScript without relying on jQuery?

I'm running into an issue where my current method of framing the ajax url seems to be caching the old response on the second call. How can I ensure that I always get the latest response? Let me know if you need more information. Snippet of Code : va ...

If the iframe's CSS source is updated, the parent's CSS source will also change

I'm currently working on a unique school project that involves creating multiple CSS styles for different views. <link rel="stylesheet" type="text/css" href="css/main.css" title="main" media="screen"> <link rel="stylesheet" type="text/css" h ...

Extract information from various files stored in Firestore

I have been struggling to retrieve data from multiple documents despite numerous attempts. The screenshot below displays that I have a collection of 3 documents, and my inquiry is how to extract data from each of them. https://i.stack.imgur.com/bFrIG.png ...

Challenges with loading content on the initial page load using the HTML5

Upon page load, I wanted to save the initial page information so that I could access it when navigating back from subsequent pages. (Initial Page -> Page2 -> Initial Page) After some trial and error, I ended up storing a global variable named first ...

The issue of Jquery selectors not functioning properly when used with variables

Currently working on a script in the console that aims to extract and display the user's chat nickname. Initially, we will attempt to achieve this by copying and pasting paths: We inspect the user's name in the Chrome console and copy its selec ...

Error occurs when JSON.parse is used

<!DOCTYPE html> <html> <head> <title></title> </head> <body> <script> var data = "{ 'name': 'John' }"; var result = JSON.parse(data); </script> ...

What is the best way to style the header of a table when scrolling in CSS?

Currently, I am facing an issue with applying the top CSS property to the thead element of a table while scrolling. I have attempted various methods but have been unsuccessful in achieving the desired outcome. Initially, I used the scroll event, however, ...

When transitioning an iOS Swift app to the background, a NodeJS error arises: 'Headers cannot be set after they have been sent to the client'

My app is built using Swift/SwiftUI. I utilize the ObservableObject and JSONDecoder to retrieve data from my Node.JS Express API and display it within the app: struct DevicesList: Decodable { var data: [DeviceInfo] } struct DeviceInfo: Decodable { ...

JQuery AJAX not retrieving data after $.post request

I am currently facing a challenge with a specific JQuery $.post request to a PHP-based processor. To troubleshoot, I set up a test page containing the following code: It's important to note that this is hosted on a subdomain, but there are no cross-d ...

Struggling to deploy a basic node.js application to Heroku or connect it with MongoDB

Currently, I'm facing some challenges trying to deploy a simple Twitter-like app to HEROKU or MongoDB. However, I seem to be hitting roadblocks with both platforms. With MongoDB, I encounter either an internal server error or the actual code displayin ...