[Python] CORS issue with fastAPI despite using a specific middleware

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

  1. Stack

    Stack Membro Participativo

    I have a CORS issue with this code from localhost:3000. I have checked the fastAPI documentation and add some code to tackle the issue. But there is no change and I have always the error.

    Here is my code :

    import httpx
    from fastapi import FastAPI
    from pydantic import BaseModel
    from starlette.middleware.cors import CORSMiddleware

    app = FastAPI()

    origins = [
    "http://localhost:3000"
    ]

    app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
    )
    app = FastAPI()
    msgs=dict()

    class Body(BaseModel):
    title: str

    class Msg(BaseModel):
    type: str
    content: dict
    @app.post("/posts/")
    async def posts(body: Body):
    number= len(msgs)+1
    title = body
    msgs[number]= {
    "type": "PostCreated",
    "data": {
    "id": number,
    "title": title.title
    }
    }
    api_url = "http://localhost:4005/events"
    async with httpx.AsyncClient() as client:
    response = await client.post(api_url, json={
    "type": "PostCreated",
    "data": {
    number, title
    }
    })

    return msgs

    @app.post("/events/")
    async def event_monitoring(msg: Msg) :
    print(msg.type)
    @app.get("/posts/")
    async def root():
    return msgs


    Here is the warning error :

    Access to XMLHttpRequest at 'http://localhost:4000/posts/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.


    localhost:3000 is the client, localhost:4000 the server.

    How to adresse this issue ?

    Continue reading...

Compartilhe esta Página