python
config_error
ai_generated
true
运行时错误:请求的资源上不存在'Access-Control-Allow-Origin'头
RuntimeError: No 'Access-Control-Allow-Origin' header is present on the requested resource
ID: python/starlette-cors-error
80%修复率
84%置信度
0证据数
2024-06-18首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
Starlette应用未配置CORS中间件,因此跨域请求被浏览器阻止。
English
Starlette application does not have CORS middleware configured, so cross-origin requests are blocked by the browser.
解决方案
-
95% 成功率 Add CORSMiddleware from Starlette
from starlette.middleware.cors import CORSMiddleware app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], ) -
90% 成功率 Use FastAPI's built-in CORS middleware if using FastAPI
from fastapi.middleware.cors import CORSMiddleware app.add_middleware(CORSMiddleware, allow_origins=["*"])
无效尝试
常见但无效的做法:
-
Adding CORS headers manually in the response
75% 失败
Doesn't handle preflight OPTIONS requests, causing browser to block the actual request.
-
Disabling CORS check in browser
90% 失败
Not a production solution; only works for local testing.