A React application fails to display JSON data fetched from a FastAPI backend at localhost:8000/todo. The data is received but is not rendered in the React UI.
This issue is caused by a lack of Cross-Origin Resource Sharing (CORS) configuration in the FastAPI backend. By default, browsers restrict cross-origin requests to prevent security risks.
To resolve this issue, CORS must be enabled in the FastAPI application. This can be achieved using the CORSMiddleware.
The following code demonstrates how to enable CORS in a FastAPI application:
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() origins = ["http://localhost:3000", "http://127.0.0.1:3000"] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], )
The CORSMiddleware allows cross-origin requests from the specified origins (http://localhost:3000 and http://127.0.0.1:3000 in this example). It also allows cookies to be included in the request (allow_credentials=True) and does not restrict HTTP methods or headers (allow_methods=["*"], allow_headers=["*"]).
The above is the detailed content of Why Isn't My React App Displaying JSON Data from My FastAPI Backend?. For more information, please follow other related articles on the PHP Chinese website!