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-fail

Also available as: JSON · Markdown · 中文
80%Fix Rate
89%Confidence
0Evidence
2024-09-12First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

CORSMiddleware is missing or misordered; in Starlette, middleware order matters and CORSMiddleware must wrap the app.

generic

中文

缺少 CORSMiddleware 或顺序错误;在 Starlette 中中间件顺序很重要,CORSMiddleware 必须包裹应用。

Workarounds

  1. 93% success
    app.add_middleware(CORSMiddleware, allow_origins=['http://localhost:3000'], allow_methods=['*'], allow_headers=['*'])
  2. 90% success
    In Flask: CORS(app, resources={r'/api/*': {'origins': 'http://localhost:3000'}})

Dead Ends

Common approaches that don't work:

  1. 75% fail

    Browsers reject wildcard with credentials.

  2. 70% fail

    Preflight OPTIONS still not handled.