python config_error ai_generated true

CORS error: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

ID: python/fastapi-cors-not-enabled

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

FastAPI 应用未启用 CORS 中间件,导致浏览器阻止跨域请求。

generic

中文

FastAPI 应用未启用 CORS 中间件,导致浏览器阻止跨域请求。

Workarounds

  1. 95% success
    from fastapi.middleware.cors import CORSMiddleware
    app.add_middleware(CORSMiddleware, allow_origins=['*'], allow_methods=['*'], allow_headers=['*'])

Dead Ends

Common approaches that don't work:

  1. 60% fail

    只处理了简单请求,预检请求(OPTIONS)仍然失败,且代码繁琐。

  2. 90% fail

    Flask-CORS 是 Flask 的扩展,不兼容 FastAPI,会导致导入错误。