DEV Community

Cover image for Connect your node backend to postgresql database
Hans
Hans

Posted on • Updated on

Connect your node backend to postgresql database

  1. npm init -> entry point: server.js

  2. create file "server.js" in project root

  3. npm install express pg nodemon

  4. in package.json add script "start":"nodemon"

{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start":"nodemon"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"nodemon": "^2.0.2",
"pg": "^7.17.1"
}
}

  1. in project root -> make folder "config"

  2. make folder db.js and add the following

const { Pool, Client } = require("pg");

const pool = new Pool({
user: 'postgres',
host: 'localhost',
database: '',
password: '',
port: 5432
});

pool.connect(err => {
if (err) {
console.error('connection error', err.stack)
} else {
console.log('connected')
}
});

  1. in file server.js add following

const express = require('express');
const app = express();
const pool = require ('./config/db');

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(Listening to port: ${PORT});
});

  1. npm start

Top comments (0)