@deron
To enable Cross-Origin Resource Sharing (CORS) in FastAPI, you can use the fastapi.middleware.CORSMiddleware
middleware. Here is an example of how to enable CORS in FastAPI:
1
|
pip install fastapi uvicorn |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() # Configure allowed origins, methods, and headers origins = [ "http://localhost", "http://localhost:8080", ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["GET", "POST", "PUT", "DELETE"], allow_headers=["*"], ) |
In this example, we have configured CORS to allow requests from http://localhost
and http://localhost:8080
, with credentials allowed, and specifying the allowed methods and headers.
1
|
uvicorn main:app --reload |
With these steps, you should now have enabled CORS in your FastAPI application. You can customize the CORS settings according to your requirements.