Become a sponsor

CORS跨域
CORS(Cross-Origin Resource Sharing)跨域资源共享是前后端分离架构必须处理的问题。通过 CORS_ALLOWED_ORIGINS 环境变量配置允许的跨域源。中间件位于 src/middleware/cors.py。
| 环境变量 | 默认值 | 说明 |
|---|---|---|
CORS_ALLOWED_ORIGINS | 空(允许所有源) | 允许的跨域源(逗号分隔) |
# .env
# 允许所有源(开发环境)
CORS_ALLOWED_ORIGINS=
# 允许指定源(生产环境)
CORS_ALLOWED_ORIGINS=https://admin.example.com,https://www.example.com生产环境
生产环境务必配置 CORS_ALLOWED_ORIGINS 为具体域名,避免允许所有源带来的安全风险。
# src/middleware/cors.py
from fastapi.middleware.cors import CORSMiddleware
from core.config.app import CORS_ALLOWED_ORIGINS
def register_cors(app):
if CORS_ALLOWED_ORIGINS:
origins = [o.strip() for o in CORS_ALLOWED_ORIGINS.split(',') if o.strip()]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
else:
# 未配置时允许所有源但不携带凭证
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=False,
allow_methods=["*"],
allow_headers=["*"],
)CORS 中间件在 core/app.py 中注册为最外层:
# 最后注册→最外层:确保限流等直接返回的响应也带 CORS 头
register_cors(app)中间件执行顺序(从外到内):
CORS → 限流 → 上传体积限制 → 操作日志 → DB会话 → Redis → 业务逻辑CORS 跨域配置具备以下特点:
1. 环境变量配置:通过 CORS_ALLOWED_ORIGINS 灵活配置允许的源
2. 开发/生产分离:开发环境允许所有源,生产环境指定域名
3. 安全默认:未配置时允许所有源但不携带凭证
4. 最外层注册:确保所有响应都带 CORS 头