Home > Mobile >  how to fetch data from flask app in react app on local server
how to fetch data from flask app in react app on local server

Time:01-28

I have a flask app running on localhost:5000:

from flask import Flask

app = Flask(__name__)   

@app.route("/api")
def parse():
    return {"test": "json"}

if __name__ == "__main__":
    # for production change debug to False
    app.run(debug=True)

And on the front end I'm fetching the data here:

  useEffect(() => {
    fetch("http://localhost:5000/api")
      .then((res) => res.json())
      .then((data: Data) => {
        setData(data);
        console.log(data);
      });
  }, []);

When I try and fetch the data from my react-app I get this error in the console:

enter image description here

I've seen a bunch of answers to similar questions, but all the other questions were more complicated than mine and I don't know what to add to my flask app since mine is pretty bare bones.

CodePudding user response:

Luckly it's pretty simple to solve it. All you need to do is to install flask-CORS with pip install flask-cors and then add an CORS header on your app, like this:

from flask_cors import CORS
from flask import Flask

app = Flask(__name__)   
CORS(app)
@app.route("/api")
def parse():
    return {"test": "json"}

if __name__ == "__main__":
    # for production change debug to False
    app.run(debug=True)

enter image description here

  • Related