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...