The issue you're experiencing stems from how your FastAPI application is structured, specifically with multiple app instances and where the CORS middleware is applied.
The Root Cause:
You've defined multiple instances of app in different modules:
-
First app instance in your main application file where you configure CORS and include routers:
# Main application file (e.g., backend/app/main.py)
app = FastAPI(
title=settings.PROJECT_NAME,
openapi_url=f"{settings.API_V1_STR}/openapi.json",
generate_unique_id_function=custom_generate_unique_id,
)
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3001"], # Allowed frontend origin
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(api_router, prefix=settings.API_V1_STR)
-
Second app instance in another module where you define the /turbines/ endpoint:
# Another module (e.g., backend/app/api/main.py)
app = FastAPI(title="Valve Calculation API")
@app.get("/turbines/", ...)
async def get_all_turbines(...):
# ...
Problem: The CORS middleware is applied only to the first app instance. When you define a new app in another module, it does not carry over the middleware or routes from the original app. As a result, the /turbines/ endpoint you're hitting does not include the necessary CORS headers, leading to the browser blocking the cross-origin request.
How to Fix It:
1. Use a Single app Instance
Ensure you're using the same FastAPI instance (app) throughout your application. Do not redefine app in multiple places.
2. Use APIRouter for Endpoints
Organize your endpoints using APIRouter. This allows you to keep your routes modular and include them in your main app.
3. Include Routers in the Main app
Make sure you include your routers in the main app where the CORS middleware is applied.
4. Adjust Your Frontend Request URL
If you have a prefix (like /api/v1) for your API, ensure your frontend fetches from the correct URL.
Applying the Fix:
Here's how you can restructure your code:
Step 1: Define your API Router
Create a router for your endpoints.
# backend/app/api/routes.py
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
from backend.app import models, schemas
from backend.app.dependencies import get_db
import logging
router = APIRouter()
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@router.get("/turbines/", response_model=List[schemas.TurbineInfo], summary="Получить все турбины")
async def get_all_turbines(db: Session = Depends(get_db)):
# Your implementation
pass
Step 2: Include the Router in the Main app
Include your router in the main application file where the app is defined and the CORS middleware is applied.
# backend/app/main.py
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from backend.app.api.routes import router as api_router # Import your router
from backend.app.core.config import settings
app = FastAPI(
title=settings.PROJECT_NAME,
openapi_url=f"{settings.API_V1_STR}/openapi.json",
generate_unique_id_function=custom_generate_unique_id,
)
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3001"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include the API router with the appropriate prefix
app.include_router(api_router, prefix=settings.API_V1_STR)
Step 3: Adjust Your Frontend Fetch URL
If your API prefix is set (e.g., settings.API_V1_STR = "/api/v1"), update your frontend request to match the correct endpoint.
// TurbineSearch.tsx
const response = await fetch('http://localhost:8000/api/v1/turbines/');
Explanation:
-
Single app Instance: By having a single app instance, all configurations, including middleware like CORS, are applied uniformly across all routes.
-
Using APIRouter: This allows you to keep your endpoint definitions modular and organized, and ensures they are included in the main app.
-
Matching API Prefix: Ensuring the frontend request URL matches the backend route (including any prefixes) is essential for the request to reach the correct endpoint.
Additional Tips:
-
Check Your Settings: Make sure settings.API_V1_STR is correctly set in your configuration. If it's "/api/v1", ensure all routes and frontend requests include this prefix.
-
Avoid Redefining app: Defining app in multiple modules can lead to confusion and unexpected behavior. Always import app from the main application module when needed.
-
CORS Middleware Placement: The CORS middleware must be applied to the app that is actually serving the requests. Applying it to an unused app instance will have no effect.
-
Testing Endpoints Directly: You can test your endpoints using tools like curl or Postman to see if they are responding correctly and include the necessary headers.
Example Directory Structure:
backend/
├── app/
│ ├── main.py # Main application file with app instance and middleware
│ ├── api/
│ │ ├── routes.py # Contains your APIRouter and endpoint definitions
│ ├── core/
│ │ ├── config.py # Contains your settings (e.g., API_V1_STR)
│ ├── models.py
│ ├── schemas.py
│ ├── dependencies.py
Final Thoughts:
By reorganizing your code to use a single app instance and appropriately including your routers, you should resolve the CORS issue and your frontend should be able to successfully fetch data from the backend.
If you continue to experience issues after making these changes, consider the following:
-
Double-Check Origins: Ensure that the origin in your CORS middleware exactly matches the origin of your frontend app (http://localhost:3001).
-
Inspect Network Traffic: Use your browser's developer tools to inspect the network requests and responses, verifying that the Access-Control-Allow-Origin headers are present.
-
Error Handling: Make sure to handle exceptions in your backend so that even error responses include CORS headers.
I hope this helps you resolve the issue!