Skip to content

Add CORS to FastAPI app #34

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions app/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,19 @@
import fastapi
import modern_di_fastapi
from advanced_alchemy.exceptions import DuplicateKeyError
from fastapi.middleware.cors import CORSMiddleware

from app import exceptions, ioc
from app.api.decks import ROUTER
from app.settings import settings


ALLOWED_ORIGINS = [
"http://localhost:5173",
# YOUR ALLOWED ORIGINS HERE
]


def include_routers(app: fastapi.FastAPI) -> None:
app.include_router(ROUTER, prefix="/api")

Expand All @@ -27,6 +34,13 @@ def __init__(self) -> None:
DuplicateKeyError,
exceptions.duplicate_key_error_handler, # type: ignore[arg-type]
)
self.app.add_middleware(
CORSMiddleware,
allow_origins=ALLOWED_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

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