python config_error ai_generated true

Response: CORS error: No 'Access-Control-Allow-Origin' header is present

ID: python/fastapi-cors-middleware-not-applied

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-04-18First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

CORS middleware not added to FastAPI app or misconfigured, causing browser to block cross-origin requests.

generic

中文

FastAPI 应用未添加 CORS 中间件或配置错误,导致浏览器阻止跨域请求。

Workarounds

  1. 95% success
    from fastapi.middleware.cors import CORSMiddleware
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_methods=["*"],
        allow_headers=["*"],
    )
  2. 90% success
    For credentialed requests: allow_origins=["https://example.com"], allow_credentials=True

Dead Ends

Common approaches that don't work:

  1. 60% fail

    Duplicated code and easy to miss; middleware is the standard way.

  2. 80% fail

    Browsers reject wildcard with credentials; must specify exact origins.