skip to Main Content

I’m running simple Flask back end

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
cors = CORS(app)


@app.route("/")
def home():
    return {"name": "John", "age": 30}


if __name__ == "__main__":
    app.run(debug=True)

and trying to log JSON on front end

function App() {

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

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

  return (
    <div className="App">
    </div>
  );
}

Also in package.json I have "proxy": "http://localhost:5000/",

No matter what I always get

JSON.parse: unexpected character at line 1 column 1 of the JSON data

What’s causing the issue and how can I fix this?

UPD:

After adding CORS and http://localhost:5000 to fetch and package.json I started to receive another error of

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/. (Reason: CORS request did not succeed). Status code: (null) Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.

UPD2:

The previous error was caused by having https instead of http in

 useEffect(() => {
    fetch("http://localhost:5000/")

3

Answers


  1. Well, if you are running your flask app in a different port, like, for example, if your backend is exposed on http://localhost:8000/ and you React app is running at http://localhost:3000/, then you need to specify the host in your fetch request, like

    useEffect(() => {
        fetch("http://localhost:8000/").then( // Or whatever is your backend host/port
            res => res.json()
        ).then(
            data => {
                setData(data);
                console.log(data);
                return data;
            }
        )
    }, [])
    

    I also suggest you to add return data; as a best practice, so you can chain multiple .then().

    It is likely that your are getting the error since the answer you are receiving, from the frontend (localhost:3000/, the one you are using by mistake) is somethin like a not found page that begins with <html> tag, that’s why you are getting the unexpected character error, since the not found page does not contains JSON, but HTML instead.

    Login or Signup to reply.
  2. your fetch url is just "/"? because if you are trying to acces a server localhost, need to set "http://localhost:YourPORT/&quot;. Try it to your fetch.
    Don’t forget to configure the CORS in your server for access locally.

    Login or Signup to reply.
  3. change your front to :

    import React, { useState, useEffect } from 'react';
    
    function App() {
      const [data, setData] = useState({}); // empty object
    
      useEffect(() => {
        fetch("/").then(
          res => res.json()
        ).then(
          data => {
            setData(data);
            console.log(data);
          }
        );
      }, []);
    
      return (
        <div className="App">
          {/* Display the data */}
          <p>Name: {data.name}</p>
          <p>Age: {data.age}</p>
        </div>
      );
    }
    

    and check your problem

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search