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

- **ID:** `python/fastapi-cors-preflight-fail`
- **领域:** python
- **类别:** network_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

缺少 CORSMiddleware 或顺序错误；在 Starlette 中中间件顺序很重要，CORSMiddleware 必须包裹应用。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.x | active | — | — |

## 解决方案

1. **** (93% 成功率)
   ```
   app.add_middleware(CORSMiddleware, allow_origins=['http://localhost:3000'], allow_methods=['*'], allow_headers=['*'])
   ```
2. **** (90% 成功率)
   ```
   In Flask: CORS(app, resources={r'/api/*': {'origins': 'http://localhost:3000'}})
   ```

## 无效尝试

- **** — Browsers reject wildcard with credentials. (75% 失败率)
- **** — Preflight OPTIONS still not handled. (70% 失败率)
