python
network_error
ai_generated
true
从源 'http://localhost:3000' 访问 'http://localhost:8000/api' 的 fetch 已被 CORS 策略阻止:请求的资源上没有 'Access-Control-Allow-Origin' 头。
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
80%修复率
89%置信度
0证据数
2024-09-12首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
缺少 CORSMiddleware 或顺序错误;在 Starlette 中中间件顺序很重要,CORSMiddleware 必须包裹应用。
English
CORSMiddleware is missing or misordered; in Starlette, middleware order matters and CORSMiddleware must wrap the app.
解决方案
-
93% 成功率
app.add_middleware(CORSMiddleware, allow_origins=['http://localhost:3000'], allow_methods=['*'], allow_headers=['*'])
-
90% 成功率
In Flask: CORS(app, resources={r'/api/*': {'origins': 'http://localhost:3000'}})
无效尝试
常见但无效的做法:
-
75% 失败
Browsers reject wildcard with credentials.
-
70% 失败
Preflight OPTIONS still not handled.