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

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

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 0.100+ | active | — | — |

## 解决方案

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(',')
   ```

## 无效尝试

- **** — Not viable for end users; masks server config bug. (99% 失败率)
- **** — Preflight OPTIONS is handled before route; header missing on OPTIONS. (85% 失败率)
