python config_error ai_generated true

RuntimeError: No 'Access-Control-Allow-Origin' header is present on the requested resource

ID: python/starlette-cors-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2024-06-18First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

Starlette application does not have CORS middleware configured, so cross-origin requests are blocked by the browser.

generic

中文

Starlette应用未配置CORS中间件,因此跨域请求被浏览器阻止。

Workarounds

  1. 95% success Add CORSMiddleware from Starlette
    from starlette.middleware.cors import CORSMiddleware
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_methods=["*"],
        allow_headers=["*"],
    )
  2. 90% success Use FastAPI's built-in CORS middleware if using FastAPI
    from fastapi.middleware.cors import CORSMiddleware
    app.add_middleware(CORSMiddleware, allow_origins=["*"])

Dead Ends

Common approaches that don't work:

  1. Adding CORS headers manually in the response 75% fail

    Doesn't handle preflight OPTIONS requests, causing browser to block the actual request.

  2. Disabling CORS check in browser 90% fail

    Not a production solution; only works for local testing.