python network_error ai_generated true

从源 'http://localhost:3000' 访问 'http://localhost:8000/api' 被 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-preflight-blocked

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

版本兼容性

版本状态引入弃用备注
0.100+ active — — —

根因分析

FastAPI/Starlette 应用未添加 `CORSMiddleware`,或中间件在路由之后添加、允许的源配置错误。

English

FastAPI/Starlette app has no `CORSMiddleware`, or the middleware was added after routes / with wrong origins.

generic

解决方案

  1. 97% 成功率
    from fastapi.middleware.cors import CORSMiddleware
    app.add_middleware(CORSMiddleware, allow_origins=['http://localhost:3000'], allow_credentials=True, allow_methods=['*'], allow_headers=['*'])
  2. 93% 成功率
    allow_origins=os.environ['ALLOWED_ORIGINS'].split(',')

无效尝试

常见但无效的做法:

  1. 99% 失败

    Not viable for end users; masks server config bug.

  2. 85% 失败

    Preflight OPTIONS is handled before route; header missing on OPTIONS.