# 运行时错误：缺少 CORS 头。请使用 'Access-Control-Allow-Origin' 头。

- **ID:** `python/starlette-cors-missing-headers`
- **领域:** python
- **类别:** config_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

Starlette 不会自动添加 CORS 头；您必须使用像 CORSMiddleware 这样的中间件。

## 版本兼容性

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

## 解决方案

1. **Add CORSMiddleware to the application** (95% 成功率)
   ```
   from starlette.middleware.cors import CORSMiddleware
app.add_middleware(CORSMiddleware, allow_origins=['*'])
   ```
2. **Use the CORSMiddleware with specific origins** (90% 成功率)
   ```
   app.add_middleware(CORSMiddleware, allow_origins=['https://example.com'], allow_methods=['GET'])
   ```

## 无效尝试

- **Manually setting headers in each response** — Preflight OPTIONS requests are not handled. (70% 失败率)
- **Using a custom middleware that only adds headers on some routes** — CORS must be applied globally. (60% 失败率)
