python network_error ai_generated true

对 /api/items 的 OPTIONS 预检请求返回 405 方法不允许

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

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

其他格式: JSON · Markdown 中文 · English
80%修复率
85%置信度
0证据数
2024-03-28首次发现

版本兼容性

版本状态引入弃用备注
0.100+ active — — —
0.110+ active — — —

根因分析

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

English

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

generic

解决方案

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

无效尝试

常见但无效的做法:

  1. 65% 失败

    Fails when CORSMiddleware is not registered first.

  2. 70% 失败

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