[Python] I have a fastapi server running on ec2 and frontend deployed over amplify. I get CORS...

Discussão em 'Python' iniciado por Stack, Dezembro 17, 2024.

  1. Stack

    Stack Membro Participativo

    I have a fastapi server running on ec2 and react frontend deployed over amplify. The backend API works fine when i call through postman, but gives CORS issue when used on frontend. The error is gone if i make the request 2 or 3 times in a row automatically.

    I did some research and found it has to do with caching the CORS configuration. My CORS config is shown in code. how do I fix this to make it work from the 1st API call.

    In the picture I have made 3 calls, and on 3rd call it works fine.

    import os
    from fastapi import FastAPI
    from fastapi.middleware.cors import CORSMiddleware
    from src.views.index import router as root_router


    app = FastAPI()

    app.add_middleware(
    CORSMiddleware,
    allow_origins=os.getenv("trusted_origins").split(","),
    allow_credentials=True,
    allow_methods=["GET", "POST", "OPTIONS"],
    allow_headers=["*"]
    )


    app.include_router(root_router)

    @app.get("/api/v0")
    def read_root():
    return {"success": {"message": "healthy", "code": 200}}



    trusted_origins=http://localhost:3002,https://api.dwellner.ca


    [​IMG]

    Continue reading...

Compartilhe esta Página