Categories

Wednesday, November 20, 2024
#919814419350 therichposts@gmail.com
Express JsNodejsPostgreSQLReactjs

Reactjs Showing PostgreSQL Data Using NodeJS Express WEB API

Reactjs Showing PostgreSQL Data Using NodeJS Express WEB API

Hello friends, welcome back to my blog. Today in this blog post, I am going to tell you, Reactjs Showing PostgreSQL Data Using NodeJS Express WEB API.

Guys in this post we will do below things:

  1. We will show data in react application with NodeJS express js web API.
  2. Solve cors issue during showing web API data.
  3. Nodejs with PostgreSQL database.
Working Demo

Reactjs Showing PostgreSQL Data Using NodeJS Express WEB API
Reactjs Showing PostgreSQL Data Using NodeJS Express WEB API
Node web api
Node web api
PostgreSQL data
PostgreSQL data

For reactjs new comers, please check the below link for basic understanding:

Reactjs Basic Tutorials


Here is the working code snippet and please use carefully and avoid mistakes:

1. Firstly friends we need reactjs fresh setup and for then we need to run below commands into our terminal and also we should have latest node version installed on our pc:

npx create-react-app reactdemo

cd reactdemo

npm start

2. Now friends we need to run below commands also to have  axios, bootstrap modules into our reactjs application:

npm install axios //API Service
npm intall bootstrap
npm start //start the application

3. Now, we need to add below code into our src/app.js file or you can replace below code with existing one that you have into your src/app.js file:

import React from 'react';
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css'

//Importing axios service
import axios from 'axios';

class App extends React.Component {
  //initialize array variable
  constructor() {

    //super is used to access the variables
    super();
    this.state = {
       data: []
    }
 }
 componentDidMount() {

 //API request
 axios.get("http://localhost:5000/users").then(response => {
  
  //getting and setting api data into variable
  this.setState({ data : response.data });
 
})
}
  
//Final output
render() {
  return (
    <div className="container p-5 App">
      
        <h1 className="text-center pb-5 border-bottom mb-5">Reactjs Showing PostgreSQL Data Using NodeJS Express WEB API</h1>
      
         <table class="table table-hover table-bordered">
         <thead>
            <tr>
                <th scope="col">ID</th>
                <th scope="col">User Name</th>
                <th scope="col">Country</th>
            </tr>
            </thead>
          <tbody>
          {this.state.data.map((result) => {
            return (

            <tr>
                <td>{result.id}</td>
                <td>{result.username}</td>
                <td>{result.country}</td>
            
            </tr>
            )})}
           
          </tbody>
        </table>
    </div>
  );
  
}

}
export default App;

Guy’s now we will do Nodejs setup and make WB API using express:

1. Guys first create empty folder name `nodebackend` inside your pc any drive and then please below commands to set node modules:

npm init  

npm i express 

npm i nodemon -D

npm i pg pg-hstore

npm i --save cors

2. Now guy’s inside your nodebackend/package.json file add below code:

{
  "name": "postgres",
  "version": "1.0.0",
  "description": "This is test project.",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "serve": "nodemon index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "pg": "^8.7.1",
    "pg-hstore": "^2.3.4",
    "sequelize": "^6.6.5"
  },
  "devDependencies": {
    "nodemon": "^2.0.12"
  }
}

3. Now guy’s create `index.js` file inside nodebackend folder and add below code inside it:

const express = require('express');

//solve cors issue
const cors = require("cors");

const app = express();

app.use(cors());
const port = 5000;
const Pool = require('pg').Pool;
  //Enter here your Postres database details
const pool = new Pool({
    user: 'postgres',
    host: 'localhost',
    database: 'dbname',
    password: 'root',
    dialect: 'postgres',
    port: 5432
});
  
  //Database connection and also please create postgres database first
pool.connect((err, client, release) => {
    if (err) {
        return console.error(
            'Error acquiring client', err.stack)
    }
    client.query('SELECT NOW()', (err, result) => {
        release()
        if (err) {
            return console.error(
                'Error executing query', err.stack)
        }
        console.log("Connected to Database !")
    })
})
  
app.get('/users', (req, res, next) => {
    console.log("TEST DATA :");
    pool.query('Select * from users')
        .then(testData => {
            console.log(testData);
            res.send(testData.rows);
        })
})

app.listen(port, () => {
  console.log(`Horror jassa app is running on port ${port}.`);
});

4. Now guy’s run below command to run NodeJS:

npm run serve

Now we are done friends. If you have any kind of query or suggestion or any requirement then feel free to comment below.

Guys in this post, I am getting data into my reactjs front-end from nodejs express backend.

Note: Friends, I just tell the basic setup and things, you can change the code according to your requirements. For better understanding must watch video above.

I will appreciate that if you will tell your views for this post. Nothing matters if your views will be good or bad.

Jassa

Thanks

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 19, MedusaJs, Next.js, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.