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
This commit is contained in:
Automated Action 2025-06-20 11:56:53 +00:00
parent 2a70291924
commit dfabc89d07

47
main.py
View File

@ -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__":