python network_error ai_generated true

405 Method Not Allowed on OPTIONS preflight request to /api/items

ID: python/fastapi-405-method-not-allowed-cors

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-03-28First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
0.100+ active — — —
0.110+ active — — —

Root Cause

CORSMiddleware added after router or with allow_methods not including OPTIONS; or route only allows POST.

generic

中文

CORSMiddleware 在路由之后添加,或 allow_methods 未包含 OPTIONS;或路由仅允许 POST。

Workarounds

  1. 93% success
    app.add_middleware(CORSMiddleware, allow_origins=['http://localhost:3000'], allow_methods=['*'], allow_headers=['*'])  # add before routes
  2. 85% success
    Ensure the route decorator uses @app.post('/api/items') and CORSMiddleware is registered at startup.

Dead Ends

Common approaches that don't work:

  1. 65% fail

    Fails when CORSMiddleware is not registered first.

  2. 70% fail

    Default allow_methods is ['GET']; OPTIONS still blocked.