Node postgres ECONNREFUSED in localhost - node.js

This issue is totally driving me insane. I spent months with this, trying to make a SIMPLE NODE APP WORK. I finally managed to make an APP work in a nice server (Heroku) and with mysql. Problem? The server only accepts postgres. And this is my nightmare. I just cannot make it work. Searched dozens of webs and problems, all of them with the same error log as me... but I just cannot figure what to do. I'm totally idiot at configuring things, I cannot even start programming my app.
Error: connect ECONNREFUSED 127.0.0.1:5432
at Object._errnoException (util.js:1022:11)
at _exceptionWithHostPort (util.js:1044:20)
at TCPConnectWrap.afteeConnect [as oncomplete] (net.js:1198:14)
My start of server.js
const pg = require('pg');
const connectionString = process.env.DATABASE_URL || 'postgres://myrole:12345#localhost:5432/mydb';
And here the error.
var pool = new pg.Pool();
pool.connect().then(client => {
It crashes right at connection.
I did everything I searched for. I created "myrole" login role with all permission, password "12345", to connect to "mydb" database. I opened "pgAdmin4" application. Connected to "PostgreSQL 10" and "mydb". I saw that the first one connects to port 3000. I tried port 3000 in the connection string. I searched for the service at Windows. It's running. I JUST DID EVERYTHING and nothing works... I installed and made MySQL database to run in local in just 2 hours. But Heroku doesn't accept MySQL and I don't want to put any credit card. What's happening here?

I was having the same issue and I'll put my situation here and hopefully help someone else.
I was testing some AWS Lambda functions and since the code runs in a container and the container has its own localhost so my postgres connection was failing because there is no postgres server running on the container. Remember that your machine's localhost is not the same as the container's one, if your app is running inside a container the instead of localhost use your machine IP.

in your case, you shuld include connectionString inside new Pool() as property of Object
var pool = new pg.Pool({connectionString}); pool.connect().then()
or here is a more detailed version
let c = {
host: 'localhost',
port: 5432,
user: 'user',
password: 'password',
database: 'mydb',
options: `application_name=${app}&application_cmd=${cmd}`
};
const connection_string = {connectionString : `postgresql://${c.user}:${c.password}#${c.host}:${c.port}/${c.database}?${c.options}`};
const pool = new Pool(connection_string);
more details can be found here node-postgres.com

Related

Unable to connect to remote redis host [nodeJS]

const redis = require('redis');
require('dotenv').config();
console.log(process.env.redisHost, ':', process.env.redisPort);
const redisClient = redis.createClient({
host: process.env.redisHost,
port: process.env.redisPort,
password: process.env.redisKey
});
redisClient.connect();
redisClient.on('error', err => console.log('Redis error: ', err.message));
redisClient.on('connect', () => console.log('Connected to redis server'));
module.exports = redisClient;
I tried this sample from redis docs but still I'm getting an error stating:
Redis error: connect ECONNREFUSED 127.0.0.1:6379
I logged the environment host and port variables to the console and I got the remote host ipv4 address, but still the client is trying to connect to localhost instead of remote host (I purposely uninstalled redis from my local device to check if the client is working as it is supposed to). I also confirmed that the remote redis host is working perfectly.
I also tried different methods like :
https://cloud.google.com/community/tutorials/nodejs-redis-on-appengine
redis.createClient(port, host, {auth_pass: password});
But still, I got the same error.
I am able to connect to the redis host via commandline:
redis-cli.exe -h XX.XX.XX.XXX -a Password
XX.XX.XX.XXX:6379> set name dhruv
OK
XX.XX.XX.XXX:6379> get name
"dhruv"
XX.XX.XX.XXX:6379> exit
I'm trying to use redis on nodejs for the first time, so don't have a proper idea but I think I am doing everything right.
Any solution/workaround will be helpful :D
It worked with this code:
const url = `redis://${process.env.redisHost}:${process.env.redisPort}`;
const redisClient = redis.createClient({
url,
password: process.env.redisKey
});
redisClient.connect();
can you check if in the destination the port is reachable. it maybe the firewall block your access

Server runs locally but crashes on Heroku

I deployed my server on Heroku but when I make any requests it returns a "500 Internal Server" error. It runs fine locally though. Could anyone help figure out what's going on?
When I check my logs this is what I'm getting.
2021-06-08T18:43:09.715406+00:00 app[web.1]: error: no pg_hba.conf entry for host "3.90.138.215", user "detmvsbueicsez", database "da9nlve42hcp91", SSL off
Repo Link: https://github.com/zcason/Restaurant-Review-Server
Live App: https://restaurant-review-phi.vercel.app/
As mentioned here on Heroku help, this indicate that there was a failed authentication attempt to the database, so the connection couldn't be established. This can happen because of different reasons.
In your case i suspect it's something related to not using ssl.
So after taking a look on the code provided in the github repo i noticed you are using knex and getting the connection string from .env
Try this :
Just add this ?ssl=true and append it to the end of DATABASE_URL in your .env file.
Edit your server.js (i didn't take a good look at the code so you need to add this ssl: { rejectUnauthorized: false } in your connection config) :
const db = knex({
client: 'pg',
connection: {
connectionString: DATABASE_URL,
ssl: { rejectUnauthorized: false }
}
});
Also make sure you're using the wright user and password and database name etc
OR Alternatively :
Run this command heroku config:set PGSSLMODE=no-verify in terminal to omit the ssl configuration object and set PGSSLMODE to no-verify

Connecting node.JS app to Heroku PostgreSQL DB

I have been having some trouble with connecting my node.JS app to my Heroku database. I had my app working with a locally hosted Postgres database on PGadmin, but when I tried moving towards deploying on Heroku with a Heroku Postgres DB I started getting a variety of errors.
This was my base code that worked locally and that I tried to switch over to Heroku's DB (some variables hidden with ***):
const Client = require('pg');
const client = new Client.Client({
host: "***.amazonaws.com",
user: "***",
password: "***",
database: "***",
port: 5432,
ssl: true,
sslmode: require,
});
The "ssl" and "sslmode" were only added when switching over.
I have triple-checked that all the values are correct. When I do it this way this is the error I get...
Error: self signed certificate
When commenting out the "ssl" part the error changes to...
Error: no pg_hba.conf entry for host '***', user '***', database '***' , SSL off
I tried researching this pg_hba.conf issue and there was suggestions I add in a line that made sure that a password was not required for all IPv4 connections but this did not change my error messages.
I am quite a bit stuck on how to solve this trouble as I can't quite find any further help online so far.

nodejs and mongodb remote access through application

I have a web app setup using nodejs and mongodb and backbonejs.
When I run my app remotely and try to redirect to a different route through the uri, for example: http://www.myapp.com/route I get a net error.
In my route.js file I have the following:
var mongodb = require('mongodb');
var db = new mongodb.Db('dbname', new mongodb.Server('xx.xx.xxx.xxx', 27017, {}));
where xx.xx.xxx.xxx is my public ip. However, when I change this to anything other than "localhost" and try to run node server.js in the root of my app I get the following error:
Listening on port 3000...
/var/www/html/pages/node_modules/mongodb/lib/server.js:236
process.nextTick(function() { throw err; })
^
Error: connect ECONNREFUSED
at exports._errnoException (util.js:746:11)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1012:19)
I have already uncommented bindIp in my /etc/mongod.conf file as suggested in other posts. I did this only to test and just to get it to work, but I plan to go back and play with the ip tables if I get this to work.
How can I access my app remotely?

Redis in Nodejs on Cloud9 IDE: [Error: Auth error: undefined]

Here is my code:
var express = require("express"),
app = express(),
server = require("http").createServer(app),
io = require("socket.io").listen(server),
redis = require("redis"),
env = {PORT: process.env.PORT || 8080, IP: process.env.IP || "localhost"};
client = redis.createClient(env.PORT , env.IP);
client.on("error", function(err) {
console.log(err);
});
server.listen(env.PORT);
console.log("Server started # " + env.IP + ":" + env.PORT);
After trying to run, I received the followings on the console:
Running Node Process
Your code is running at 'http://modified.address.c9.io'.
Important: use 'process.env.PORT' as the port and 'process.env.IP' as the host in your scripts!
info: socket.io started
Server started # modified.ip.address.1:8080
[Error: Auth error: undefined]
I tried establishing the connection, and it connects to the IP and PORT perfectly. However, the error [Error: Auth error: undefined] appears and stops there. I Googled the error, the supports from the IDE I used..., and surprisingly, there are only 7 links to my problems. So I think it may be a hole in my knowledge or it is not really a problem yet a thing I don't know to work it out. All I could pull out from those Google results were (I was not sure) I need to use client.auth(pass) right after creating it. But where should I find the password? When I installed it npm install redis I didn't configure anything and wasn't told to set password whatsoever. So I reach the impasse.
I use Cloud9 IDE (c9.io), and the modules used as shown in the code above.
----With best regards,
----Tim.
I've found out what was wrong.
I did install Redis, but that is a Redis library that acts like a bridge between Redis driver and NodeJS. On Cloud9, I have to manually install Redis, too.
So it would take 2 commands to actually install Redis:
Install the Redis Driver on Cloud9
nada-nix install redis
Install Redis library for NodeJS
npm install redis
Thanks for anyone who was trying to help me.
You can run the redis-server using your own config file.You can create your own config like below.
//port and ip of ur redis server
port 6371
bind 127.0.0.1
//password for this server
requirepass ucanmentionurpwd
//storing snapshots of the data
save 60 1
dbfilename dump.rdb
dir /tmp/db
//starting redis server
redis-server //ur config file location
See this link for redis configuration
https://raw.github.com/antirez/redis/2.6/redis.conf
If you mention requirepass with your password means only you need to do
client.auth('urPwd');
Otherwise no need to call the client.auth method.

Resources