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

Issue with Discord.js reminder command: An expected numerical value was not provided

Hey there, I'm having an issue with my reminder command as it keeps giving me a TypeError: Expected a number if(command === "remind"){ let timeuser = args[0] let reason = args.slice(1).join(" ") // !remind 10m Dream Code Uploaded ...

Action creator incomplete when route changes

In my React-Redux application, there is an action creator that needs to make 4 server calls. The first three calls are asynchronous and the fourth call depends on the response of the third call. However, if a user changes the route before the response of t ...

Tips for linking server value with Javascript onmousedown in an aspx web page

I have a single Hyperlink on an aspx page. There are two tasks I need to accomplish: When I click on the hyperlink, I want to log some activity. While logging the EmployeeID value, I need to bind it from the server. However, I am encountering an error t ...

Using routing with modules instead of components in Angular 10+ involves configuring the routing paths within the module files

I recently tried implementing modules instead of components for routing in Angular 10, but encountered a white screen issue. Any assistance would be greatly appreciated. Here is the code snippet I've been working with: import { NgModule } from &apos ...

I am looking to dynamically fill my form fields with data retrieved from my database through an AJAX call to another PHP file

I am attempting to dynamically populate my form fields with data retrieved from a database row using ajax. The goal is to send the id of the row I need when a specific button is clicked. Although I have managed to successfully fetch the desired row in the ...

bootstrap thumbnail displayed without a border

I have decided to incorporate Bootstrap into my latest project: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS ...

Creating a Self Closing Alert Message in AngularJS: A Step-by-Step Guide

Just getting started with AngularJS and looking to create a self-closing message. How can this be accomplished? I'm aiming for similar results as the question found here: How to Automatically Close Alerts using Twitter Bootstrap However, I want to ...

Exploring the World of Browserify Submodules

/xyz /abc.js /abcdef.js /index.js When working with node.js, if you use the require statement for a directory (require('xyz')), it will automatically search for an index.js file within that directory and return the exports defined in that ...

Troubleshooting issue with Mongoose's populate() function not functioning as expected

I am working with a PaymentCard schema and a User schema. My goal is to specify an existing user's ID when creating a new PaymentCard record in order to link that particular card to that specific customer. The issue I am facing is that although the pa ...

getting information from component in NextJS

Apologies if this question is too basic. I recently started my journey into learning React and NextJS. I am working on a simple application that fetches data and displays it on the Home page. In my component file, I have two functions. This component file ...

Exploring the power of AngularJS with JavaScript and utilizing the $scope

After spending the entire day trying to solve this issue, it seems like I might be missing something simple. Here's the problem at hand: I have a well-structured Nodejs/AngularJS application that utilizes Jade for templating. The server performs certa ...

Guide on assigning JSON response values to TypeScript variables in Angular 4

I'm just starting with Angular 4 and I'm attempting to retrieve a JSON value using http.post. The response I'm receiving is: {"status":"SUCCESS"} component onSubmit(value: any) { console.log("POST"); let url = `${this.posts_Url}`; t ...

Steps for importing a json file into Chrome

Inside my file named data.json, there is a JSON object structure: { "k": : "..some object...", "a": [ "...", "bbb" ] } When working with Node.js, I can easily import this data into a variable using: let data = require("./data.json"); However, how can I ...

Updating the color of tick marks on checkboxes

I have successfully updated the background color of my checkboxes using a custom function. However, the tick mark on the checkbox now turns black instead of remaining white. How can I keep the tick mark white while changing the background color? Here is t ...

Showcasing interactive column titles by employing angularjs in an html table

After preparing my data, I aim to showcase it in an HTML table. However, a complication arises each time the $http service is called as it returns a varying number of columns (n). Essentially, I wish to have the first row of the data serve as column names, ...

The console is displaying the array, but it is not being rendered in HTML format in AngularJS

Can you please review my App.js file and let me know if there are any mistakes? I have provided the necessary files index.html and founditemtemplate.html below. Although it is returning an array of objects in the console, it is not displaying them as inten ...

There seems to be a glitch in my JavaScript for loop as it is not iterating for the correct amount that it should

It seems like my for loop is not always iterating 7 times as intended. Sometimes it runs with 5 iterations, other times with 4 or 3. This is the JavaScript code I am using: var start = new Date().getTime(); var end = new Date().getTime(); function timeT ...

How to accentuate search results using Angular filters and conceal non-matching text?

Recently, I came across an interesting example of using Angular filter to highlight search results. It works well in highlighting the word 'suit', but I noticed that all non-matching text remains visible. If you'd like to see the example I ...

Angular 2 orderByPipe not displaying any results initially

At first, I thought the reason for not displaying anything initially was due to it not being async and returning an empty array. Everything worked fine without the pipe, but the posts weren't shown on startup. After submitting a post, all the posts ap ...

Creating a new route in Node.js by blocking it

I'm currently developing a node js app and I need to disable certain urls on my platform for all users. Is this feasible? Just to clarify, I want the ability to toggle registration and authentication on and off. Update: I am utilizing the express js f ...