python
network_error
ai_generated
true
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-header-missing
80%Fix Rate
90%Confidence
0Evidence
2024-03-30First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
CORSMiddleware is not installed or does not include the requesting origin, so the browser blocks the response.
generic中文
未安装 CORSMiddleware 或其允许的源不包含请求来源,因此浏览器阻止了响应。
Workarounds
-
95% success
from fastapi.middleware.cors import CORSMiddleware app.add_middleware(CORSMiddleware, allow_origins=['http://localhost:3000'], allow_credentials=True, allow_methods=['*'], allow_headers=['*'])
-
88% success
app.add_middleware(CORSMiddleware, allow_origin_regex=r'https://.*\.example\.com')
Dead Ends
Common approaches that don't work:
-
90% fail
Browsers reject wildcard origin when credentials are included.
-
95% fail
Not possible for end users; only a local dev flag.