fix: handle OPTIONS preflight before routing to fix CORS 400

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 <noreply@anthropic.com>
This commit is contained in:
vee1e 2026-06-02 13:38:45 +05:30
parent 5b209c718c
commit b9bf24ef71
No known key found for this signature in database
GPG key ID: EB498AFC60A7A01A

View file

@ -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