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;
2
Answers
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: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.
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:
Back Code: