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.
Related
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;
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
I have looked around for a solution, but I can't seem to figure this out. What I'm trying to do is make POST/GET requests to a PostgreSQL database from an Express server.
main.js:
var app = require('../app');
var debug = require('debug')('server:server');
var http = require('http');
var port = normalizePort(process.env.PORT || '8000');
app.set('port', port);
var server = http.createServer(app);
server.listen(port, () => {
console.log(`Server is running on localhost:${port}`);
});
server.on('error', onError);
server.on('listening', onListening);
app.js:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var helmet = require('helmet');
var indexRouter = require('./routes');
var app = express();
app.use(cors());
app.use(helmet());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
module.exports = app;
routes.js (Handling the api requests)
router.post('/api/post/userprofiletodb', async (req, res, next) => {
console.log(req);
const values = [req.body.profile.nickname, req.body.profile.email, req.body.profile.email_verified];
// ON CONFLICT DO NOTHING - prevents the user profile from being stored in db twice
await pool.query(`INSERT INTO users(username, email, email_verified, date_created)
VALUES($1, $2, $3, NOW() )
ON CONFLICT DO NOTHING`, values,
(q_err, q_res) => {
if (q_err) return next(q_err);
console.log(q_res);
res.json(q_res.rows);
})
})
router.get('/api/get/userprofilefromdb', async (req, res, next) => {
console.log(req);
const email = String(req.query.email);
await pool.query(`SELECT * FROM users WHERE email=$1`, [email],
(q_err, q_res) => {
if (q_err) return next(q_err);
res.json(q_res.rows);
})
})
db.js:
const { Pool } = require('pg');
const pool = new Pool({
user: 'postgres',
host: 'localhost',
database: 'mydb',
password: 'mypassword',
post: 5432
});
module.exports = pool;
React code (Action Creators for Redux):
export const setDbProfile = (profile) => async(dispatch) => {
const response = await axios.post('http://localhost:8000/api/post/userprofiletodb', profile);
dispatch({ type: SET_DB_PROFILE, payload: response.data });
console.log(response);
history.replace('/');
}
export const getDbProfile = (profile) => async(dispatch) => {
const data = profile;
console.log('getDbProfile', profile);
const response = await axios.get('http://localhost:8000/api/get/userprofilefromdb',
{
params: {
email: data.profile.email
}
}
)
dispatch({ type: GET_DB_PROFILE, payload: response.data });
history.replace('/');
Here is my thought process:
- I have my Express server set up on http://localhost:8000 and my React application is running on http://localhost:3000 (I have already included a proxy in the package.json file).
- When the action creator is called, it first does a post request to http://localhost:8000 where my Express server is on.
- The Express server sees this and makes a request to the PostgreSQL database stored on localhost: 5432.
However, I'm getting this error....
POST /api/post/userprofiletodb 500 182.558 ms - 250
Error: connect ECONNREFUSED 127.0.0.1:5432
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1117:14)
GET /api/get/userprofilefromdb?email=dasfdfasfdf#gmail.com 500 52.541 ms - 250
Error: connect ECONNREFUSED 127.0.0.1:5432
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1117:14)
I think there may be an issue with my PostgreSQL database. How I set that up is by opening up SQL Shell (psql) and did the following:
- CREATE DATABASE mydb;
- \c mydb
- CREATE TABLE users(...);
- CREATE TABLE posts(...);
- CREATE TABLE comments(...);
Not too sure how I could solve this... Any guidance would be greatly appreciated! Cheers.
UPDATE:
When I run the command
netstat -na
I do not see, 127.0.0.1.5432 listed at all... Does this mean my database is just not setup properly?
Running SQL Shell (psql)
x-MacBook-Air:~ x$ /Library/PostgreSQL/12/scripts/runpsql.sh; exit
Server [localhost]:
Database [postgres]:
Port [5000]: 5432
Username [postgres]:
psql: error: could not connect to server: could not connect to server: Connection refused
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
Press <return> to continue...
so I am working on the backend of my web app. I keep getting this error: password authentication failed for user "postgre"
const express = require("express")
const router = express.Router()
const Pool = require('pg').Pool
const pool = new Pool({
user: 'postgre',
host: 'localhost',
database: 'p2p',
password: 'hello',
port: 5432,
})
router.get('/',(req,res)=>{
res.render('physician/login')
})
//table: doc_reg,
router.post('/loggedin',(req,res)=>{
const {user_name,pw_1}=req.body
pool.query('INSERT INTO doc_reg (username,pw) VALUES ($1,$2)',[user_name,pw_1],(err, results)=>{
if (err){
console.log(err)
}
res.render('physician/loggedin',{username:user_name})
})
})
module.exports=router
Anything went wrong here?
Generally, this error occurs when you are using the wrong password for the given user.
The flowing code successfully connects mongoose with the mlab database on localhost and Heroku. But it's not working on Namecheap node js Server.
const express = require("express");
const mongoose = require("mongoose");
const port = parseInt(process.env.PORT, 10) || 3000;
const server = express();
mongoose.connect("mongodb://#ds213645.mlab.com:13645/techblog", {
useNewUrlParser: true,
auth: {
user: "user",
password: "pass"
}
});
const Schema = mongoose.Schema;
const userSchema = new Schema(
{
name: String,
email: String
},
{ timestamps: true }
);
const User = mongoose.model("User", userSchema);
server.get("/test", async (req, res) => {
const user = new User({ name: "SomeName", email: "your#email.com" });
const userData = await user.save();
res.send(userData);
});
server.get("/", async (req, res) => {
res.send("working");
});
server.listen(port, err => {
if (err) throw err;
console.log(`> Ready on ${port}`);
});
When I hit the root('/') route it works perfectly on Namecheap server but when I hit test('test') route it response 'Incomplete response received from application' after a long time. So what is the way to connect mongoose with the database on Namecheap shared hosting?
Issue solved.
The problem was Namecheap. Namecheap blocked outgoing request on port 13645. After contacting them they opened outgoing request on port 13645
Contact namecheap support and ask them to open the ports below
ports:
27017
3000
443 and
80
at the first is used in local or MLAB if is MLAB try the same
mongoose.connect(MONGO_URI);
mongoose.connection
if used the MongoDB in local try to run the mongo server from go to the location
C:\Program Files\MongoDB\Server\4.0\bin and run mongo then run Mongod after then try to run the project enter image description here
"//"name user and password
: MustName_user:password //#ds213645.mlab.com:13645/techblog", {