From b9bf24ef719f32a20f5d0cf3b653966487fe7b4b Mon Sep 17 00:00:00 2001 From: vee1e Date: Tue, 2 Jun 2026 13:38:45 +0530 Subject: [PATCH] fix: handle OPTIONS preflight before routing to fix CORS 400 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The fallback middleware was calling call_next first, so OPTIONS hit the router (no handler → 400) before headers could be injected. Intercept OPTIONS early and return 200 with CORS headers directly. Co-Authored-By: Claude Sonnet 4.6 --- backend/main.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/backend/main.py b/backend/main.py index 34f4f39..c89de93 100644 --- a/backend/main.py +++ b/backend/main.py @@ -38,11 +38,22 @@ app.add_middleware( @app.middleware("http") async def add_cors_header(request: Request, call_next): + from starlette.responses import Response as StarletteResponse + if request.method == "OPTIONS": + return StarletteResponse( + status_code=200, + headers={ + "access-control-allow-origin": "*", + "access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS, PATCH", + "access-control-allow-headers": "*", + "access-control-max-age": "600", + }, + ) response = await call_next(request) origin = request.headers.get("origin", "") if origin and "access-control-allow-origin" not in response.headers: response.headers["access-control-allow-origin"] = "*" - response.headers["access-control-allow-methods"] = "GET, POST, PUT, DELETE, OPTIONS" + response.headers["access-control-allow-methods"] = "GET, POST, PUT, DELETE, OPTIONS, PATCH" response.headers["access-control-allow-headers"] = "*" return response