skip to Main Content

I have 2 files, App.js, which just contains a button, that should write to the console, after calling a function, that connects to the Database. The other file is Database.jsx, which makes the database connection.

As a beginner with React, I’m having a really hard time getting data from the database.
If Database.jsx was a file that should run in client side, I could just import it into App.js, but since it should run on server, importing it throws a lot of exceptions. So I’ve found out that I can use Axios to communicate with backend.

Clicking on the <Button onClick={() => getData()}>Show</Button>, I just want to write the data to the console.

So how do I let axios.get(http://localhost:3000/getData) in my App.js know that the getData, is in the Database.jsx, and how do I make the Database.jsx to actually listen on income on the given URL?

In my App.js I have

import { Button } from "react-bootstrap";
import axios from "axios";

function App() {  
    const getData = async () => {
        console.log('Clicked');

        axios.get(`http://localhost:3000/getData`)
            .then((res) => {
                setData(res.data)
                console.log(data);
            })
            .catch((err) => console.log(err));
    }

    return (
        <div className='contentDiv'>
            <Button onClick={() => getData()}>Show</Button>
        </div>
    )
}

In my Database.jsx, I have

const { Client } = require('pg');
const { default: axios } = require('axios');

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

axios.get('/getData', async (req, res) => {
  client.connect();

  client.query('SELECT * FROM movies', (err, res) => {
    if (err) {
      console.error(err);
      return;
    }
    const rows = res.rows;
    client.end();

    return rows;
  })
})

I found this: Fetch data from PostgreSQL into React react

which seems similar to what I want, but the guy who explains, uses express. What confuses me, is that he’s creating another server with express, that is listening. But doesn’t reach have its on sever built in? As you can see in my: axios.get(http://localhost:3000/getAdmins), React is already listening, so I’m confused why I should make another server with express?

I don’t mind if I must use axios, fetch or any other tool to achieve this, just what you can help with. Thanks

4

Answers


  1. axios is used to make call to APIs and not backend. You have to create a server using express.js and make DB calls from there. Currently you are trying to manipulate data on client side which is not possible. Creating an Express server will help you out. Moreover, be sure that your port of server will be different from client and URLs will change accordingly.

    Login or Signup to reply.
  2. Answer 1/3

    So how do I let axios.get(http://localhost:3000/getData) in my App.js
    know that the getData, is in the Database.jsx, and how do I make the
    Database.jsx to actually listen on income on the given URL?

    Re: This is the point. To let the API call, axios.get(http://localhost:3000/getData) to find the API code is in Database.jsx and also to make code inside Database.jsx listens to the incoming API call, you need an additional piece of software. ExpressJS is an easy and quick solution here. Just in a few lines of code, you can make it ready. Please see an example code below.

    package.json

    {
      "dependencies": {
        "express": "^4.20.0"
      }
    }
    

    server.js

    const express = require('express');
    const app = express();
    
    app.get('/getData', (req, res) => {
      res.send('some dummy data');
    });
    
    app.listen(3000, () => console.log('l@3000'));
    

    Install the dependencies

    npm install // this will install express
    

    Running the server

    node server.js // this will run the server we created above
    

    Testing the server

    Request url : http://localhost:3000/getdata , type it in the browser
    Response : some dummy data
    Status : The basic server works fine.
    
    Login or Signup to reply.
  3. Answer 2/3

    Now we need to incorporate the database access in the server.

    package.json

    // the same code modified with database access
    {
      "dependencies": {
        "express": "^4.20.0",
        "pg": "^8.12.0"
      }
    }
    

    server.js

    const express = require('express');
    const { Client } = require('pg');
    const app = express();
    let client;
    
    app.get('/getData', (req, res) => {
      client.query('SELECT * FROM movie', (err, result) => {
        if (err) {
          res.sendStatus(500).send(err);
          return;
        }
        const rows = result.rows;
        res.send(rows);
      });
    });
    
    app.listen(3000, () => {
      console.log('l@3000');
      client = new Client({
        user: 'postgres',
        host: 'localhost',
        database: 'postgres',
        password: 'test',
        port: 5432,
      });
      client.connect();
    });
    

    Install the dependencies

    npm install // this will install express
    

    Running the server

    node server.js // this will run the server we created above
    

    Testing the server

    Request url : http://localhost:3000/getdata , type it in the browser
    Response : 
    [
      {
        "description": "movie-one                                                   ",
        "releasedyear": "2000"
      },
      {
        "description": "movie-two                                                   ",
        "releasedyear": "2010"
      },
      {
        "description": "movie-three                                                 ",
        "releasedyear": "2020"
      }
    ]
    
    Status : The basic server works fine with the database.
    
    Login or Signup to reply.
  4. Answer 3/3

    which seems similar to what I want, but the guy who explains, uses
    express. What confuses me, is that he’s creating another server with
    express, that is listening. But doesn’t reach have its on sever built
    in? As you can see in my: axios.get(http://localhost:3000/getAdmins),
    React is already listening, so I’m confused why I should make another
    server with express?

    Re: React does not have this capability. It is just a frontend application library. Do not worry. Now with the same server we created above, your same React app will work and fetch data. Please see the same code below.

    server.js

    const express = require('express');
    const { Client } = require('pg');
    const cors = require('cors');
    
    const app = express();
    app.use(cors());
    
    let client;
    
    app.get('/getData', (req, res) => {
    
      client.query('SELECT * FROM movie', (err, result) => {
        if (err) {
          res.sendStatus(500).send(err);
          return;
        }
        const rows = result.rows;
        res.send(rows);
      });
    });
    
    app.listen(4000, () => {
    
      console.log('l@4000');
      client = new Client({
        user: 'postgres',
        host: 'localhost',
        database: 'postgres',
        password: 'test',
        port: 5432,
      });
      client.connect();
    });
    

    App.js

    import { Button } from 'react-bootstrap';
    import axios from 'axios';
    
    export default function App() {
      const getData = async () => {
        console.log('Clicked');
    
        axios
          .get(`http://localhost:4000/getData`)
          .then((res) => {
            console.log(res.data);
          })
          .catch((err) => console.log(err));
      };
    
      return (
        <div className="contentDiv">
          <Button onClick={() => getData()}>Show</Button>
        </div>
      );
    }
    

    Test run:

    node server.js // this will start the backend server
    node start // this will start the React app
    

    Clicking on show button:
    The data accessed from the database, and shown in the console as below.

    data fetched from the database

    I don’t mind if I must use axios, fetch or any other tool to achieve
    this, just what you can help with. Thanks

    Re: axios or the built-in fetch function can be used.

    Notes:

    1. You may face some issues with creating the appropriate directories to host the frontend app and the backend server as it has not been clarified in this post. You may please post your comment in this regard, shall help based on it.
    2. Please note the change in port number. The reference to the port 3000 has been changed to 4000.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search