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
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.
解决方案
-
93% 成功率
app.add_middleware(CORSMiddleware, allow_origins=['http://localhost:3000'], allow_methods=['*'], allow_headers=['*']) # add before routes
-
85% 成功率
Ensure the route decorator uses @app.post('/api/items') and CORSMiddleware is registered at startup.
无效尝试
常见但无效的做法:
-
65% 失败
Fails when CORSMiddleware is not registered first.
-
70% 失败
Default allow_methods is ['GET']; OPTIONS still blocked.