python
network_error
ai_generated
true
CORS: origin 'http://example.com' not allowed by Access-Control-Allow-Origin
ID: python/fastapi-cors-error-origin-not-allowed
80%Fix Rate
85%Confidence
0Evidence
2024-05-12First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.9 | active | — | — | — |
| 3.10 | active | — | — | — |
Root Cause
FastAPI 应用未正确配置 CORS 中间件以允许特定来源
generic中文
FastAPI 应用未正确配置 CORS 中间件以允许特定来源
Workarounds
-
95% success 使用 CORSMiddleware 并添加允许的来源
from fastapi.middleware.cors import CORSMiddleware app.add_middleware(CORSMiddleware, allow_origins=['http://example.com'])
-
90% success 允许所有来源(仅用于开发)
app.add_middleware(CORSMiddleware, allow_origins=['*'])
Dead Ends
Common approaches that don't work:
-
只在前端设置请求头而不修改后端
95% fail
CORS 策略由服务器控制,前端无法绕过
-
在 FastAPI 中手动添加响应头但未使用中间件
70% fail
可能被其他中间件覆盖或处理不当