python network_error ai_generated true

从源 'http://localhost:3000' 访问 'http://localhost:8000/api' 的 fetch 被 CORS 策略阻止:请求的资源上没有 'Access-Control-Allow-Origin' 响应头。

Access to fetch at 'http://localhost:8000/api' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

ID: python/fastapi-cors-header-missing

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

版本兼容性

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

根因分析

未安装 CORSMiddleware 或其允许的源不包含请求来源,因此浏览器阻止了响应。

English

CORSMiddleware is not installed or does not include the requesting origin, so the browser blocks the response.

generic

解决方案

  1. 95% 成功率
    from fastapi.middleware.cors import CORSMiddleware
    app.add_middleware(CORSMiddleware, allow_origins=['http://localhost:3000'], allow_credentials=True, allow_methods=['*'], allow_headers=['*'])
  2. 88% 成功率
    app.add_middleware(CORSMiddleware, allow_origin_regex=r'https://.*\.example\.com')

无效尝试

常见但无效的做法:

  1. 90% 失败

    Browsers reject wildcard origin when credentials are included.

  2. 95% 失败

    Not possible for end users; only a local dev flag.