python network_error ai_generated true

Access to fetch at 'http://localhost:8000/api' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

ID: python/fastapi-cors-preflight-blocked

Also available as: JSON · Markdown · 中文
80%Fix Rate
90%Confidence
0Evidence
2024-02-27First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
0.100+ active — — —

Root Cause

FastAPI/Starlette app has no `CORSMiddleware`, or the middleware was added after routes / with wrong origins.

generic

中文

FastAPI/Starlette 应用未添加 `CORSMiddleware`,或中间件在路由之后添加、允许的源配置错误。

Workarounds

  1. 97% success
    from fastapi.middleware.cors import CORSMiddleware
    app.add_middleware(CORSMiddleware, allow_origins=['http://localhost:3000'], allow_credentials=True, allow_methods=['*'], allow_headers=['*'])
  2. 93% success
    allow_origins=os.environ['ALLOWED_ORIGINS'].split(',')

Dead Ends

Common approaches that don't work:

  1. 99% fail

    Not viable for end users; masks server config bug.

  2. 85% fail

    Preflight OPTIONS is handled before route; header missing on OPTIONS.