PostgreSQL error: `Error: connect ECONNREFUSED 127.0.0.1:5432` - node.js

I'm trying to make a request to postgreSQL from a Node and Express server on localhost. But I keep getting this error Error: connect ECONNREFUSED 127.0.0.1:5432 when trying to open localhost:8000/todos - not sure why.. I changed the username to 'postgres' (which is the defualt username), password, host, database name and port are all correct.. I can check the todos using SELECT * FROM todos; however, the app just breaks and gives me that code. I made sure that the server is running. I started it in services, and I can check the content of todos (which I manually added) in the SQL shell. Any ideas on why this is happening? I've gone thru all the other pages with similar issue, but I'm pretty new to postgreSQL overall and I'm unable to find an answer. I'm not using docker.
this is the exact error in the console:
Server runnnig on PORT 8080
Error: connect ECONNREFUSED 127.0.0.1:5432
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1487:16) {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 5432
}
main server.js
const PORT = 8080;
const express = require("express");
const app = express();
const pool = require("./db");
app.get("/todos", async (req, res) => {
try {
const todos = await pool.query("SELECT * FROM todos");
res.json(todos.rows);
} catch (err) {
console.error(err);
}
});
app.listen(PORT, () => console.log(`Server runnnig on PORT ${PORT}`));
db.js file where the connection is coming from
const Pool = require("pg").Pool;
require("dotenv").config();
const pool = new Pool({
user: "postgres",
password: process.env.PASSWORD,
host: "localhost",
port: 5432,
database: "todoapp",
});
module.exports = pool;

Related

Cannot connect to GCP Postgres database with Sequelize

I have created a database in GCP but when I try to connect it with my Node.js server on localhost I'm getting the following error:
original: Error: connect ETIMEDOUT 35.202.153.108:5432
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16) {
errno: -4039,
code: 'ETIMEDOUT',
syscall: 'connect',
address: '35.202.153.108',
port: 5432
}
Here is my code in db.js:
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize(
process.env.DATABASE_NAME,
process.env.DATABASE_USERNAME,
process.env.DATABASE_PASSWORD,
{
host: process.env.DATABASE_HOST,//35.202.153.108
dialect: 'postgres',
}
);
module.exports = sequelize;
db.authenticate()
.then((t) => console.log('Connection has been established successfully.'))
.catch((error) => console.error('Unable to connect to the database:', error));
Can someone help me with connecting to GCP database?
Try this one:
Create a TCP connection by using Node.js
const createTcpPool = config => {
// Extract host and port from socket address
const dbSocketAddr = process.env.DB_HOST.split(':'); // e.g. '127.0.0.1:5432'
// Establish a connection to the database
return Knex({
client: 'pg',
connection: {
user: process.env.DB_USER, // e.g. 'my-user'
password: process.env.DB_PASS, // e.g. 'my-user-password'
database: process.env.DB_NAME, // e.g. 'my-database'
host: dbSocketAddr[0], // e.g. '127.0.0.1'
port: dbSocketAddr[1], // e.g. '5432'
},
// ... Specify additional properties here.
...config,
});
};
The link as well content several other examples for TCP, Socket, SQL and even how to retry connections to Cloud SQL for Postgres in Google Cloud using node.js, php and some others.
You need to use Cloud SQL Proxy to connect to your Cloud SQL from localhost. Then your app connects with the Cloud SQL Proxy with host name=localhost.
Basically, after setting up Cloud SQl Proxy, your app acts like the database is hosted locally but it is actually talking with the Proxy and Proxy is talking with your Cloud SQL instance.

Heroku error: "connect ECONNREFUSED 127.0.0.1:3306" when trying to deploy Express + React application

I was trying to deploy my Express + React application to Heroku. Heroku connected successfully with my Github account, then clicking "Deploy Branch" led to "Your app was successfully deployed". But when I went to view my website, it showed:
"Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details".
Here are my logs:
Starting process with command `npm start`
> myproject# start /app
> node backend/index.js
My project SQL server listening on PORT 4000
/app/backend/index.js:22
if (err) throw err;
^
Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)
And the index.js which connects to MySQL:
const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const app = express();
app.use(cors());
app.get('/', (req, res) => {
res.send('go to /my-project to see my project')
});
const pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: 'root',
password: 'myjs123#',
database: 'my-project',
debug: false
});
pool.getConnection((err, connection) => {
if (err) throw err;
app.get('/my-project', (req, res) => {
connection.query(SELECT_ALL_FACTS_QUERY, (err, results) => {
if (err) {
return res.send(err)
}
else {
return res.json({
data: results
})
};
});
});
});
const SELECT_ALL_FACTS_QUERY = 'SELECT * FROM `my-project`.`my-table`;';
app.listen(4000, () => {
console.log('My project SQL server listening on PORT 4000');
});
What did I do wrong and how could I deploy it?
I think in the below code the localhost should not be used, the localhost will not work in deployment.
const pool = mysql.createPool({
connectionLimit: 10,
//here
host: 'localhost',
user: 'root',
password: 'myjs123#',
database: 'my-project',
debug: false
});
And another mistake I found is you should use an environment variable to store
port numbers. In production, the port number is assigned by Heroku, if not assigned you
can assign. So your code should be
let port=process.env.PORT||4000
app.listen(port, () => {
console.log(`App running on port ${port} `);
});
you need to add (add-ons) to your heroku account
and connect it to your app.
For example, you can use (JAWS_DB mysql)
By having the following code in your connection:
// import the Sequelize constructor from the library
const Sequelize = require('sequelize');
require('dotenv').config();
let sequelize;
// when deployed on Heroku
if (process.env.JAWSDB_URL) {
sequelize = new Sequelize(process.env.JAWSDB_URL);
} else {
// localhost
sequelize = new Sequelize(process.env.DB_NAME,
process.env.DB_USER,
process.env.DB_PASSWORD, {
host: 'localhost',
dialect: 'mysql',
port: 3306
});
}
module.exports = sequelize;
It passed this stage after I removed if (err) throw err;, still not sure why this happened.
Nithin's answer was taken into account too.
the same errorhappened to me while i was trying to connect to heroku cli and i jus read the heroku config for proxy and that was the case. problem solved by configuring the http and https proxy like
set HTTP_PROXY=http://proxy.server.com:portnumber
or set HTTPS_PROXY=https://proxy.server.com:portnumber

How to connect to postgresql database inside AWS EC2 instance using Node.js and Knex

I rented an EC2 instance of Ubuntu 16.xx on AWS and installed PostgreSQL on it. I created a database and table inside the PostgreSQL on EC2. Right now I am trying to connect to and get data from the database via a local Node.js project using knex.
I already enabled the inbound rule for port 5432 to IP from anywhere.
However, it returns error message as below:
Error: connect ECONNREFUSED 13.229.xxx.xxx:5432
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1142:16) {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '13.229.xxx.xxx',
port: 5432
}
How am I gonna fix it? Do I need to install and implement a reversed proxy? If so, how do I set it up? I know there is RDS on AWS, but I need to use EC2 to implement it.
Here are some of my codes:
This is the knex setting, I have pg installed. The connection to a local database is successful. But when I switch the host to whether a public IP/ private IP/ ec2-13-229-xxx-xxx.ap-southeast-1.compute.amazonaws.com. They all return the above error message.
development: {
client: 'postgresql',
connection: {
host: '13.229.xxx.xxx',
database: 'project2',
user: 'postgres',
password: 'postgres',
port: 5432,
},
pool: {
min: 2,
max: 10,
},
migrations: {
tableName: 'knex_migrations',
},
},
This is the Node.js code that I used to connect to the server. A very simple one, just to test the connection.
const express = require('express');
const hbs = require('hbs');
const app = express();
const knexConfig = require('./knexfile')['development'];
const knex = require('knex')(knexConfig);
let query = knex.select('*').from('users');
query
.then((data) => {
console.log(data);
})
.catch((err) => console.log(err));
This is my firewall setting which is turned off
Also, I paused my Kaspersky.
This is my pg_hba.conf file
And I am not sure where to add the permission of my personal IP.
This issue was related to the pg_hba.conf being restricted to localhost only.
Additionally the postgres.conf needed to have listen_addresses = '*'.
By whitelisting outside access, it was possible to access the database.
Additional support from this article.

problem about connecting to my Postgres with node.js through knex

I am facing this problem with connecting to my Postgres with node.js through knex. I am trying this for the first time and I ask humbly to help me solving the issue. please help me.
My code is the following. Every time I make a request, PostgreSQL doesn't connect so nothing happens.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
const bcrypt = require('bcrypt-nodejs');
const cors = require('cors');
const knex = require('knex')
const db = knex({
client: 'pg',
connection: {
host: '127.0.0.1',
user: 'postgres',
password: '',
database: 'smart-brain'
}
});
db.select('*').from('users').then(console.log).catch(console.log);
app.use(cors());
app.post('/signin', (req, res) => {
if (req.body.email === database.users[0].email &&
req.body.password === database.users[0].password) {
res.json('success');
} else {
res.status(400).json('error logging in');
}
})
app.post('/register', (req, res) => {
const {
name,
email,
password
} = req.body;
db('users')
.returning('*')
.insert({
email: email,
name: name,
joined: new Date()
})
.then(respons => {
res.json(response);
}).
catch(err => res.status(400).json('unable to register'))
})
app.listen(3000, () => {
console.log('app is running on the port 3000');
});
and the response is these on npm
Error: connect ECONNREFUSED 127.0 .0 .1: 5432
at TCPConnectWrap.afterConnect[as oncomplete](net.js: 1141: 16) {
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 5432
}
If you are in Ubuntu, then go to the following folder.
/etc/postgresql/{your_pg_version}/main
Or If you are in Windows, then go to the following folder,
C:\Program Files\PostgreSQL\{your_pg_version}\data\
Open the file pg_hba.conf to write with SuperUser/Administrative permission,
Go to the bottom, and put trust at the end of following lines.
# Database administrative login by Unix domain socket
local all postgres trust
# "local" is for Unix domain socket connections only
local all all trust
# IPv4 local connections:
host all all 127.0.0.1/32 trust
After that, restart your PostgreSQL server and try again with your code.

Error when connecting to postgresql on localhost with knex

I am trying to connect to my local postgres db with knex but I keep getting this error.
{ Error: connect ECONNREFUSED 127.0.0.1:5432
at Object.exports._errnoException (util.js:1022:11)
at exports._exceptionWithHostPort (util.js:1045:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14)
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 5432 }
// Here is how everything is set up:
const connection = require('./db/knexfile.js').development;
const knex = require('knex')(connection);
const app = express();
const server = app.listen(PORT, '127.0.0.1', 'localhost', () => console.log(`Listening on ${ PORT }`));
// Inside knexfile.js
module.exports = {
development: {
client: 'pg',
connection: {
"user": "development",
"password": "development",
"database": "testdb",
"host": "127.0.0.1",
"port": 5432
},
pool: {
min: 2,
max: 10
},
migrations: {
tableName: 'knex_migrations'
}
}
};
Additional information:
I am also running a React front end through webpack on localhost:3000 that sends http requests to 8080 through a proxy setting on the webpack server but this seems to be working.
I also have elasticsearch running on localhost:9200 and that seems to be wroking, too.
The issue was that I had an incorrect version of postgres installed. I reinstalled postgres and no longer had the issue.
Another, faster, approach is to connect to a local database is to use AF_UNIX sockets. You will have to give access rights to the Linux user that will host the application:
development:
connection: {
host: '/var/run/postgresql', // On Debian it is this one, check your distro
database: 'database_name'
},
This kind of access was measured to be 30% faster than going through AF_INET (TCP/IP) sockets.
Here an old article about that: Performance of UNIX sockets vs TCP sockets

Resources