From d8896839b60edd47975472b0bf0595914d4f317c Mon Sep 17 00:00:00 2001 From: Kowshik Deb Nath Date: Mon, 11 Mar 2024 19:51:28 +0600 Subject: [PATCH] Issue #284 Add CORS support to handle preflight OPTIONS requests This commit addresses the CORS issue reported in Issue #284, where the API failed to handle preflight OPTIONS requests, causing failures in direct client-to-API communications from browsers. The FastAPI application now includes CORSMiddleware, allowing proper handling of CORS preflight checks and enabling browser-based clients to directly interface with the Canopy API. Changes: - Added CORSMiddleware to the FastAPI application setup. - Configured the middleware to allow all origins, methods, and headers, facilitating cross-origin requests. This update ensures better accessibility and integration capabilities of the Canopy API for various client applications, especially those running in browser environments. --- src/canopy_server/app.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/canopy_server/app.py b/src/canopy_server/app.py index 69c048d0..557da311 100644 --- a/src/canopy_server/app.py +++ b/src/canopy_server/app.py @@ -23,6 +23,10 @@ Body, APIRouter ) + +from fastapi.middleware.cors import ( + CORSMiddleware +) import uvicorn from typing import cast, Union, Optional @@ -89,6 +93,15 @@ async def lifespan(app: FastAPI): }, lifespan=lifespan ) + +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], # Allows all origins + allow_credentials=True, + allow_methods=["*"], # Allows all methods + allow_headers=["*"], # Allows all headers +) + openai_api_router = APIRouter() context_api_router = APIRouter(prefix="/context") application_router = APIRouter(tags=["Application"])