skip to Main Content

I have a fast api get function in python:

from fastapi import FastAPI
app = FastAPI()

@app.get("/json/")
async def json_re():
    data = [
        {
            "id": 1,
            "name": "abc",
            "username": "Bret",
            "email": "[email protected]",
        }
    ]
    return data

if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=8888)

And then the associated react code:

  const [data, setData] = useState(null);
  const fetchData = () => {
      return fetch('http://127.0.0.1:8888/json/', {
        method: 'GET'
    })
      .then((res) => res.json())
      .then((d) => 
      {
        window.alert(d);
        setData(d);
      })
  };

  useEffect(() => {
    fetchData();
  }, []);

This is the fast api i get from the js fetch:

INFO: 127.0.0.1:63112 - "GET /json/ HTTP/1.1" 200 OK

But the window.alert(d); is never executed. When i use some open api like https://jsonplaceholder.typicode.com/users everything is working.
So there must be an error with my fast api. I also tried to create a response with

from fastapi.responses import JSONResponse
from fastapi.responses import Response

return Response(content=data, media_type="application/json")

But no improvements.

FURTHER INFO

I get the following error in my console output:

Access to fetch at 'http://127.0.0.1:8888/json/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

2

Answers


  1. You don’t mention how you are running your applications, it could be a network issue.

    If you are certain the application should be reachable, you can try to rewrite the code a bit to also enable error handling.

    const [data, setData] = useState(null);
    
    const fetchData = () => {
      fetch('http://127.0.0.1:8888/json/', { method: 'GET' })
        .then((res) => {
          if (!res.ok) {
            throw new Error(`HTTP error ${res.status}`);
          }
          return res.json();
        })
        .then((d) => {
          setData(d);
        })
        .catch((error) => {
          console.error("Fetch failed:", error);
        });
    };
    
    useEffect(() => {
      fetchData();
    }, []);
    

    Please provide more context if you can, any errors you see in the dev console or logs.

    Login or Signup to reply.
  2. you can use axios package for call API

    import axios from ‘axios’;

    axios.get('your_URL).then((res) => {
          console.log(res);
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search