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
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.
Please provide more context if you can, any errors you see in the dev console or logs.
you can use axios package for call API
import axios from ‘axios’;