python network_error ai_generated true

CORS: origin 'http://example.com' not allowed by Access-Control-Allow-Origin

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

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.9 active
3.10 active

Root Cause

FastAPI 应用未正确配置 CORS 中间件以允许特定来源

generic

中文

FastAPI 应用未正确配置 CORS 中间件以允许特定来源

Workarounds

  1. 95% success 使用 CORSMiddleware 并添加允许的来源
    from fastapi.middleware.cors import CORSMiddleware
    app.add_middleware(CORSMiddleware, allow_origins=['http://example.com'])
  2. 90% success 允许所有来源(仅用于开发)
    app.add_middleware(CORSMiddleware, allow_origins=['*'])

Dead Ends

Common approaches that don't work:

  1. 只在前端设置请求头而不修改后端 95% fail

    CORS 策略由服务器控制,前端无法绕过

  2. 在 FastAPI 中手动添加响应头但未使用中间件 70% fail

    可能被其他中间件覆盖或处理不当