skip to Main Content

Im following a youtube tutorial (https://www.youtube.com/watch?v=7LNl2JlZKHA&t=300s) in order to setup a webapp using Flask and React. Ive followed the turotial pretty closley (other than having issues with a venv, which i fixed by not using one). Everything compiles, but I keep getting an error in my console instead of what is expected (small string of data).

Backend Code:

from flask import Flask

app= Flask(__name__)

# Members API Route
@app.route("/members")
def menbers():
    return {"members": ["Member1","Member2","Member3"]}


if __name__ =="__main__":
    app.run(host='0.0.0.0')

Frontend Code:

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

function App() {
  const [data, setData] = useState([{}]);

  useEffect(() => {
    fetch("/members")
      .then(res => res.json())
      .then(data => {
        setData(data);
        console.log(data);
      });
  }, []);

  return (
    <div>
      {data.map((member, index) => (
        <div key={index}>{/* Render member data here */}</div>
      ))}
    </div>
  );
}

export default App;

The Error I get in my console

2

Answers


  1. I believe the problem is on the line fetch("/members"), since you are providing just the path, not the full URI. Your fetch should be something like this:

    const host = '0.0.0.0'; // Apparently your server is on this address
    const port = 1234; // Here you must put the same port that your backend is using.
    fetch(`http://${host}:${port}/members`)
    

    This way you’re pointing exactly to your server’s address. You just need to confirm which address and port your backend is running on.

    Login or Signup to reply.
  2. I checked the YouTube video that you listed, and based on the information you provided, there are two things that may have gone wrong in your code. Firstly, an error that I faced while replicating your code was a Cross-Origin Resource Sharing (CORS) issue, where I wasn’t allowed to exchange shared resources. For this, the fix was quite easy, and this thread might help you out. The second issue that you were facing was an Uncaught (in promise) SyntaxError. The reason for this error is that your React project did not know what to render in the placeholder for data while it was waiting for the data from the API. The fix for this was in your YouTube video, which rendered a simple <p> tag with a “Loading…” text while it was waiting for the data. Once loaded, it then displays the data received from the API. Here is the updated code for both your front and back:

    Front Code:

    import React, { useState, useEffect } from 'react';
    
    function App() {
      const [data, setData] = useState([{}]);
    
    
      useEffect(() => {
        fetch("http://127.0.0.1:5000/members")
          .then(res => res.json())
          .then(data => {
            setData(data);
            console.log(data);
          });
      }, []);
    
      return (
        <div>
          {(typeof data.members === 'undefined') ? (
            <p>Loading...</p>
          ) : (
          data.members.map((member, index) => (
            <p key={index}>{member}</p>
          ))
    
    
        )}
        </div>
      );
    }
    
    export default App;
    

    Back Code:

    from flask import Flask
    from flask_cors import CORS
    
    app = Flask(__name__)
    CORS(app)
    # Members API Route
    
    @app.route("/members")
    def menbers():
        return {"members": ["Member1", "Member2", "Member3"]}
    
    if __name__ == "__main__":
        app.run(debug=True)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search