Home > Net >  Fetching data using React to a Python backend
Fetching data using React to a Python backend

Time:08-17

I am using python (bottle framework) as backend and React as frontend. I want to fetch data from React through "http://127.0.0.1:8080/" using useEffect Hook. The problem is I keep getting:

enter image description here

Here is my backend (python)

@get('/')
def _():
    data = {
        'name': 'Alvin',
        'lastname': 'Johnson'
    }
    return json.dumps(data)

And here is the frontend (react)

import React, { useEffect, useState } from 'react';

import './App.css';

function App() {

  const [data, setdata] = useState({
    name: '',
    lastname: ''
  });

  useEffect(() => {
    fetch('/').then((res) =>
      res.json()).then((data) => {
        console.log(data);
        setdata({
          name: data.name,
          lastname: data.lastname
        });
      })
  }, []);

  return (
    <div className="App">
      <h1>Welcome to Python-React app</h1>
      <p>{data.name}</p>
      <p>{data.lastname}</p>
    </div>
  );
}

export default App;

I have also added "proxy" on package.json file

"proxy":"http://127.0.0.1:8080/",

Is there anything I am doing wrong? Thank you in advance.

CodePudding user response:

consider using axios, thats what I use for my Flask backend.

import axios from 'axios';
import React, { useEffect, useState } from 'react';
import './App.css';

function App() {

  const [data, setdata] = useState({
    name: '',
    lastname: ''
  });

  const fetchData = async () => {
      const response = await axios.get(`http://127.0.0.1:8080/`)
      setdata(response.data);
      }

  useEffect(() => {
    fetchData(); 
      }, [])

  return (
    <div className="App">
      <h1>Welcome to Python-React app</h1>
      <p>{data.name}</p>
      <p>{data.lastname}</p>
    </div>
  );
}

export default App;
  • Related