python config_error ai_generated true

RuntimeError: CORS headers are missing. Use 'Access-Control-Allow-Origin' header.

ID: python/starlette-cors-missing-headers

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-08-22First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

Starlette does not automatically add CORS headers; you must use a middleware like CORSMiddleware.

generic

中文

Starlette 不会自动添加 CORS 头;您必须使用像 CORSMiddleware 这样的中间件。

Workarounds

  1. 95% success Add CORSMiddleware to the application
    from starlette.middleware.cors import CORSMiddleware
    app.add_middleware(CORSMiddleware, allow_origins=['*'])
  2. 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:

  1. Manually setting headers in each response 70% fail

    Preflight OPTIONS requests are not handled.

  2. Using a custom middleware that only adds headers on some routes 60% fail

    CORS must be applied globally.