Retrieving data from database between client and server

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

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.

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.

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.

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.

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.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật