python config_error ai_generated true

fastapi.exceptions.HTTPException: 500 Internal Server Error: CORS error: Origin http://localhost:3000 is not allowed.

ID: python/fastapi-cors-origin-not-allowed

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

跨域请求来源未在 CORS 配置中允许。

generic

中文

跨域请求来源未在 CORS 配置中允许。

Workarounds

  1. 95% success
    from fastapi.middleware.cors import CORSMiddleware\napp.add_middleware(CORSMiddleware, allow_origins=['http://localhost:3000'], allow_methods=['*'], allow_headers=['*'])
  2. 90% success
    allow_origin_regex='https?://localhost:3000'

Dead Ends

Common approaches that don't work:

  1. 70% fail

    未处理预检请求,且配置繁琐。

  2. 80% fail

    当 allow_credentials=True 时,不能使用通配符。