Skip to content

Commit c4368c8

Browse files
Add CORS to FastAPI app (#34)
* Add CORS to FastAPI app * fix format --------- Co-authored-by: Artur Shiriev <[email protected]>
1 parent e9cbf15 commit c4368c8

File tree

2 files changed

+76
-58
lines changed

2 files changed

+76
-58
lines changed

app/application.py

+14
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,19 @@
44
import fastapi
55
import modern_di_fastapi
66
from advanced_alchemy.exceptions import DuplicateKeyError
7+
from fastapi.middleware.cors import CORSMiddleware
78

89
from app import exceptions, ioc
910
from app.api.decks import ROUTER
1011
from app.settings import settings
1112

1213

14+
ALLOWED_ORIGINS = [
15+
"http://localhost:5173",
16+
# YOUR ALLOWED ORIGINS HERE
17+
]
18+
19+
1320
def include_routers(app: fastapi.FastAPI) -> None:
1421
app.include_router(ROUTER, prefix="/api")
1522

@@ -27,6 +34,13 @@ def __init__(self) -> None:
2734
DuplicateKeyError,
2835
exceptions.duplicate_key_error_handler, # type: ignore[arg-type]
2936
)
37+
self.app.add_middleware(
38+
CORSMiddleware,
39+
allow_origins=ALLOWED_ORIGINS,
40+
allow_credentials=True,
41+
allow_methods=["*"],
42+
allow_headers=["*"],
43+
)
3044

3145
@contextlib.asynccontextmanager
3246
async def lifespan_manager(self, _: fastapi.FastAPI) -> typing.AsyncIterator[dict[str, typing.Any]]:

0 commit comments

Comments
 (0)