From dfabc89d07c9205a9e418b42ed895a7de37941ae Mon Sep 17 00:00:00 2001 From: Automated Action Date: Fri, 20 Jun 2025 11:56:53 +0000 Subject: [PATCH] Fix CORS configuration for frontend access - Added custom CORS middleware to ensure headers are always present - Added explicit OPTIONS handler for preflight requests - Used both custom and standard CORS middleware for maximum compatibility - This should definitively resolve CORS blocking issues --- main.py | 47 +++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 43 insertions(+), 4 deletions(-) diff --git a/main.py b/main.py index 3a3e997..7c06ab1 100644 --- a/main.py +++ b/main.py @@ -1,7 +1,8 @@ import logging from contextlib import asynccontextmanager -from fastapi import FastAPI +from fastapi import FastAPI, Request, Response from fastapi.middleware.cors import CORSMiddleware +from fastapi.middleware.base import BaseHTTPMiddleware from app.db.session import engine from app.db.base import Base from app.routers import monitors, checks, scheduler @@ -15,6 +16,33 @@ logger = logging.getLogger(__name__) Base.metadata.create_all(bind=engine) +class CORSMiddleware2(BaseHTTPMiddleware): + async def dispatch(self, request: Request, call_next): + # Handle preflight requests + if request.method == "OPTIONS": + response = Response() + response.headers["Access-Control-Allow-Origin"] = "*" + response.headers["Access-Control-Allow-Methods"] = ( + "GET, POST, PUT, DELETE, OPTIONS" + ) + response.headers["Access-Control-Allow-Headers"] = "*" + response.headers["Access-Control-Max-Age"] = "3600" + return response + + # Process the request + response = await call_next(request) + + # Add CORS headers to the response + response.headers["Access-Control-Allow-Origin"] = "*" + response.headers["Access-Control-Allow-Methods"] = ( + "GET, POST, PUT, DELETE, OPTIONS" + ) + response.headers["Access-Control-Allow-Headers"] = "*" + response.headers["Access-Control-Expose-Headers"] = "*" + + return response + + @asynccontextmanager async def lifespan(app: FastAPI): # Startup @@ -34,6 +62,10 @@ app = FastAPI( lifespan=lifespan, ) +# Add custom CORS middleware +app.add_middleware(CORSMiddleware2) + +# Also add the standard CORS middleware as backup app.add_middleware( CORSMiddleware, allow_origins=["*"], @@ -63,10 +95,17 @@ async def health_check(): return {"status": "healthy", "service": "uptime-monitoring-api"} -@app.options("/{path:path}") -async def options_handler(): +@app.options("/{full_path:path}") +async def options_handler(full_path: str): """Handle preflight OPTIONS requests""" - return {"message": "OK"} + from fastapi import Response + + response = Response() + response.headers["Access-Control-Allow-Origin"] = "*" + response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS" + response.headers["Access-Control-Allow-Headers"] = "*" + response.headers["Access-Control-Max-Age"] = "3600" + return response if __name__ == "__main__":