Postgres error in NodeJS: Cannot resolve address - ENOTFOUND

My connection string for accessing my AWS database is

pg://user:pass@localhost:port/table
. It works perfectly fine when connecting to localhost, but as soon as I attempt to connect to the AWS server, everything falls apart.

Even a simple connection code results in an error message. The name of the database is 'people' and it's running on port 8080, but despite declaring the correct port number in the conString, the error message shows 5432 instead.

Error: getaddrinfo ENOTFOUND people people:5432 at errnoException (dns.js:26:10) at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:77:26)

Below is the code snippet I've been using:

var pg = require("pg");

var conString = "pg://someuser:pass@db-endpoint:8080/postgres";
var client = new pg.Client(conString);
client.connect();

Answer №1

If you are confident that your connection string is properly formatted as described by gnerkus, the final thing to investigate is your password. If it contains non-alphanumeric characters, that could be the source of the problem. It appears that either Node.js or the inner workings of JavaScript itself may be causing this issue (although I cannot confirm this as pg-admin connects fine using my original password).

My password contained special characters such as '+' and '/' (generated by creating a lengthy JSON filled with random text and then hashing it to produce a base64 string). When I removed these characters from both my connection string and database password, the issue was resolved.

Interestingly, the character '=' was actually acceptable. The problem seemed to stem from the URL decoding process on the database side. Sending '+' likely caused it to be replaced with a space, leading to an incorrect password. Meanwhile, the presence of '/' resulted in a malformed URL, triggering the "not found" error. Consider the following scenario:

postgres://username:sdkadady88da8+8ahdajd/ashdi==@localhost/database

The surplus '/' here causes the URL to break down incorrectly. As a result,

protocol:// user:pass@host / database
transforms into
protocol:// [malformed user:pass@host] / [malformed database name] / [some gibberish]
. This can be traced back to the additional '/'.

If your colleague accessing it via JSF has the ability to adjust their connection string, I recommend updating the password to one that satisfies both systems. Otherwise, consider setting up another user/account with identical permissions but a different password suitable for use with Node.js.

EDIT: Furthermore, based on suggestions from this discussion, attempting to encode the password section of your connection string might resolve the issue. Although I did not personally test this method after changing my own password, given that you continue experiencing difficulties, it would be wise to explore this solution prior to adopting one of the aforementioned approaches.

Answer №2

During my recent project, I encountered an issue while trying to establish a database connection within a docker container. The problem stemmed from using the incorrect DB_HOST value - I mistakenly entered the docker service name instead of 'localhost'.

Fortunately, once I corrected the DB_HOST setting, the issue was quickly resolved.

Erroneous .env configuration: DB_HOST=postgres

Corrected .env configuration: DB_HOST=localhost

Answer №3

Encrypting your password for security.

let encryptedPassword = `${encodeURIComponent(database.dbPassword)}@`;

Answer №4

By default, the port used for connecting to a Postgres database is usually 5432. This means that the Postgres database running on AWS is most likely using this port as well. When creating your connection string, make sure it follows this structure:

var conString = "postgres://username:password@localhost/database";

This format is outlined in the node-postgres documentation. Therefore, you must modify your connection string to the following:

var conString = "postgres://someuser:pass@db-endpoint:5432/people";

Answer №5

If anyone encounters this problem, I'll leave it here for reference

My mistake was using 127.0.0.1:5432 instead of just 127.0.0.1

Answer №6

Ensure that your URL does not include the prefix http://

Answer №7

I recently discovered that my password was not accepting the dollar sign. After removing it, everything worked perfectly.

Answer №8

When providing the host to the pool class, ensure you write it as "address string" and not as "@address string." This small detail can make a big difference in how your code functions.

Answer №9

In my experience, I encountered an issue while trying to establish a connection to a PostgreSQL database hosted on AWS from an API deployed on Heroku using the pg npm package. The solution was to modify the PGHOST environmental variable by removing the 'https://' prefix from the URL link in order to connect successfully.

Answer №10

Most of the time, the issue lies with the password. It's best to use a straightforward combination of letters and numbers for security.

Answer №11

In a unique and unusual turn of events, I encountered an issue where my DATABASE_URL was set as an environment variable with double quotes around it in a .env file. The original line looked something like this: DATABASE_URL="pg://someuser:pass@db-endpoint:8080/postgres"

While this setup worked perfectly fine during local testing, it caused problems on my deployment platform (Netlify). The solution? Simply removing the double quotes from the DATABASE_URL in my Netlify environment variables: DATABASE_URL=pg://someuser:pass@db-endpoint:8080/postgres

The reason for the double quotes in the first place was that I copied this format directly from my cloud-hosted database at Cockroach Labs.

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

Tips for utilizing the node package dotenv to interact with environment variables in a Red Hat OpenShift application during local development

After neglecting a project for some time, I am now revisiting it. In the production/online environment, the code relies on environment variables set in: openshift online console > applications > deployments > my node app > environment For th ...

What causes useEffect to trigger twice when an extra condition is included?

Attempting to create a countdown timer, but encountering an interesting issue... This code triggers twice in a row, causing the useEffect function to run twice per second. 'use client' import {useState, useEffect, useRef} from 'react' ...

Developing a system mode called "night mode"

I've decided to incorporate a dark mode feature into my Wordpress theme. Creating both dark and light modes was a breeze, but now I want to add a third mode that serves as the default for pages. This new mode will automatically switch between dark a ...

What is the reason behind the inconsistency of express session in creating cookies?

I have configured my express server to use cookies in the following way: app.use( session({ secret: "someStringForSecretKey", resave: false, store: new redisstore({ client: RL }), saveUninitialized: false, cookie: { ma ...

Tips for concealing navigation buttons during certain stages in react stepzilla

When working with React Stepzilla, I encountered an issue where I have five steps but need to hide the next button on the first step. Following different methods provided online such as: const steps = [ {name: 'Step 1', com ...

Choosing a particular 2D array based on another variable in jQuery and JavaScript

Within my project, I am utilizing 2D arrays to append specific divs under particular circumstances. In an effort to streamline and enhance the code, I attempted to create a variable that would determine which array to utilize based on the id of an HTML < ...

Looking for guidelines on Node, Express, and Jade styling?

Having previous experience in PHP, I am used to using 4 spaces for tabs. However, I have noticed that in many examples and project bootstrap code, only 2 spaces are used. I have searched for definitive style guides for these projects but have not found a ...

Error: The function stripHtml cannot be found

Currently, I am developing a blog website using Next Js. I encountered an issue while creating a rich text-editor API for the blog. When attempting to utilize string-strip-html, an error message was displayed as follows: C:\Users\alami\OneDr ...

A step-by-step guide on initializing and setting a cookie value with expiration

Below is the code I have added. Can someone please help me locate the bug? Here is the code snippet: $_SESSION['browser'] = session_id(); setcookie($expire, $_SESSION['browser'], time() + (60 * 1000), "/"); echo "Value is: " . $_COO ...

The function $(...) does not recognize tablesorter

Currently, I am encountering issues with the tablesorter plugin as my system is unable to recognize the existing function. It is unclear whether there might be a conflict with other JavaScript files, especially since I am implementing changes within a Word ...

AJAX allows developers to declare variables within their code to

Here is a snippet of my JavaScript code: $(\"img.agree\").click(function() { var follow_id = $(this).attr(\"id\"); var user_id = $(\"img.user_id\").attr(\"id\"); $.ajax({ type: \"POST& ...

Vue.js - Resetting child components upon array re-indexing

I am working with an array of objects const array = [ { id: uniqueId, childs: [ { id: uniqueId } ] }, { id: uniqueId, childs: [ { id: uniqueId } ] }, ] and I have a looping structure ...

Changing the color of HTML text based on a variable in Vue JS can be achieved by altering the CSS styles dynamically

I have developed a website that shows values with a set threshold. I now want to change the color of the values when they exceed the threshold, but I am unsure of how to proceed. I want to display consultation.indicateurs.TRS in red when it exceeds the va ...

Performing multiple asynchronous operations on a set of data using node.js

Currently, I am in the process of developing a nodejs application and I am still learning about nodejs's asynchronous model. The issue at hand is that I have made changes to a database collection by adding a string field while still referencing anoth ...

my combination of express and socket.io run on separate ports

My Express 4 application always starts on port 3000, ignoring socketIO in this port. When I explicitly listen to a different port after binding my Express app with Socket.IO, Express + Socket start on the specified port (e.g., 3030) and I can run my app on ...

What causes the return of undefined when accessing an item from an object?

In order to extract the item "Errors" from the data object provided below: {Id: 15, Date: "22-02-2019", Time: "22:45", Sport: "Football", Country: "United Kingdom", …} Bet: "Win" Bookie: "Bet365" Competition: "Premier League" Country: "U ...

Retrieve the value of a CSS class property regardless of whether it is actively being utilized

I am facing a dilemma where I need to determine the value of the 'width' property for a css class named 'foo' (example: ".foo { width:200px}" ). However, there may not be an element with this class in the dom yet. My goal is to retrie ...

Error: jQuery is unable to access the property 'xxx' because it is undefined

While attempting to make a post request from the site to the server with user input data, I encountered an error message saying TypeError: Cannot read property 'vehicle' of undefined as the response. Here is the HTML and script data: <!DOCTY ...

Deleting a row from a table in AngularJS can be accomplished by following these steps

I am having trouble with deleting rows from a table using angularjs. When I try to delete a row, it ends up deleting the previous row instead of the correct one. How can I fix this issue? Please check out the working DEMO Here is the code snippet: < ...

When incorporating axios within an express route, it is causing the data field to display unusual characters instead of JSON

I've been grappling with this issue for quite some time now, and any assistance would be greatly appreciated. Initially, I attempted to resolve the problem by utilizing the Moralis nodeJs library. While it worked fine on my local environment, it retu ...