python config_error ai_generated true

FastAPI HTTP 异常:500 内部服务器错误,CORS 错误:不允许的来源 http://localhost:3000。

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

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

其他格式: JSON · Markdown 中文 · English
80%修复率
87%置信度
0证据数
2024-06-08首次发现

版本兼容性

版本状态引入弃用备注
3.x active

根因分析

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

English

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

generic

解决方案

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

无效尝试

常见但无效的做法:

  1. 70% 失败

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

  2. 80% 失败

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