python network_error ai_generated true

跨域预检请求未通过:响应缺少 'Access-Control-Allow-Origin' 头

Access to fetch at 'http://api.local/items' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present.

ID: python/fastapi-cors-preflight-failed

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

版本兼容性

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

根因分析

缺少 CORSMiddleware,或 allow_origins 与浏览器来源不匹配,导致预检 OPTIONS 请求失败。

English

CORSMiddleware is missing or configured with allow_origins that don't match the browser origin, so preflight OPTIONS requests fail.

generic

解决方案

  1. 93% 成功率
    Add middleware before app start:
    app.add_middleware(CORSMiddleware, allow_origins=['http://localhost:3000'], allow_methods=['*'], allow_headers=['*'])
  2. 88% 成功率
    List explicit origins when using credentials.

无效尝试

常见但无效的做法:

  1. 80% 失败

    Browsers reject wildcard origin when credentials are included.

  2. 70% 失败

    Preflight is answered before the route runs, so manual headers don't apply to OPTIONS.