python
config_error
ai_generated
true
RuntimeError: CORS headers are missing. Use 'Access-Control-Allow-Origin' header.
ID: python/starlette-cors-missing-headers
80%Fix Rate
85%Confidence
0Evidence
2024-08-22First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
Starlette does not automatically add CORS headers; you must use a middleware like CORSMiddleware.
generic中文
Starlette 不会自动添加 CORS 头;您必须使用像 CORSMiddleware 这样的中间件。
Workarounds
-
95% success Add CORSMiddleware to the application
from starlette.middleware.cors import CORSMiddleware app.add_middleware(CORSMiddleware, allow_origins=['*'])
-
90% success Use the CORSMiddleware with specific origins
app.add_middleware(CORSMiddleware, allow_origins=['https://example.com'], allow_methods=['GET'])
Dead Ends
Common approaches that don't work:
-
Manually setting headers in each response
70% fail
Preflight OPTIONS requests are not handled.
-
Using a custom middleware that only adds headers on some routes
60% fail
CORS must be applied globally.