python network_error ai_generated true

Access to fetch at 'http://api.local/items' 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.

ID: python/fastapi-cors-preflight-failed

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

CORSMiddleware is missing or configured with allow_origins that don't match the browser origin, so preflight OPTIONS requests fail.

generic

中文

缺少 CORSMiddleware,或 allow_origins 与浏览器来源不匹配,导致预检 OPTIONS 请求失败。

Workarounds

  1. 93% success
    Add middleware before app start:
    app.add_middleware(CORSMiddleware, allow_origins=['http://localhost:3000'], allow_methods=['*'], allow_headers=['*'])
  2. 88% success
    List explicit origins when using credentials.

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Browsers reject wildcard origin when credentials are included.

  2. 70% fail

    Preflight is answered before the route runs, so manual headers don't apply to OPTIONS.