Home > other >  Connect to postgres with nodeJS
Connect to postgres with nodeJS

Time:01-25

Im struggling to create API call to my database from node.js. i have a postgres instance on Centos with multiple databases and table. im trying to get table name "test_reslts" from database "sizing_results". when the url, its just the server ip and port like http://{SERVER IP}:3300/ this is output - "Cannot GET /" when adding the table name or db name and table name, the request isn't completed and not output.

my code - db_connection

const {Client} = require('pg')

const client = new Client({
  user: 'postgres',
  database: 'sizing_results',
  password: 'password',
  port: 5432,
  host: 'localhost',
})

module.exports = client

api.js

const client = require('./db_connection.js')
const express = require('express'); // To make API calls 
const app = express();

app.listen(3300, ()=>{
    console.log("Server is now listening at port 3300");
})

client.connect();

app.get('/test_results', (req, res)=>{
    client.query(`select * from test_results`, (err, result)=>{
        if(!err){
            res.send('BLABLA')
            res.send(result.rows);
        }
    });
    client.end;
})

CodePudding user response:

Base on your answer to my comment I think it's not a DB connection problem.

It seems to be link to your routing, because it seems node never reach the inside of your route.

Are you sure you are calling the good route (http://localhost:3300/test_results) with no typo ? And with the good protocol (GET) ?

CodePudding user response:

You just need to do better error handling. Response can't be sent more than once.

app.get('/test_results', (req, res)=>{
    client.query(`select * from test_results`, (err, result)=>{
        if(err){
            res.send(err);
        }
            res.send('BLABLA')
            res.send(result.rows);
        }
    });
    client.end;
})

  • Related