Home > Software design >  Parse JSON in React JS from Python Flask
Parse JSON in React JS from Python Flask

Time:10-28

I'm new to React JS and just start working on a project with React JS as frontend and Python Flask 2.2.2 as the backend. In Flask I'm trying to return a JSON in a function:

@app.route('/profile')
def test():
    response_body = {
        "test123": "123",
        "name": "Owen!",
        "about": "about!"
    }
    print(f"response is {response_body}")
    return Response(response_body, status=200, mimetype='application/json')

Basically, it will just return a JSON object(Flask will automatically convert it to JSON as I learned). And then in JS I used axios to call the backend and get the response like this:

axios
            .get("/profile")
            .then(response =>
                console.log(response.data.about)
            )
            .catch(error => {});

I also did some research that axios and JS will automatically convert the JSON to Javascript object so "response.data.about" should give me the result in JSON returned from Flask. But I'm actually getting undefined in console. Could anyone please point me to where it is wrong? Many thanks in advance!

CodePudding user response:

Your server and your client aren't running on the same port so you need fetch to the actual route of the flask backend

axios.get("http://localhost:8080/profile")
     .then(response => console.log(response.data.about))
     .catch(error => {});

Replace that 8080 with the port your backend is running on.

CodePudding user response:

After I changed the return type in Python from

return Response(response_body, status=200, mimetype='application/json')

to directly return the body

return response_body

Then I can get the json value directly: response.data.test123. Not clear for the reason, but will look more into this.

  • Related