修复跨域问题

This commit is contained in:
2026-04-14 12:50:02 +08:00
parent bf5b2516e2
commit a29b3f0711
4 changed files with 26 additions and 3 deletions

View File

@@ -32,6 +32,7 @@ async def lifespan(app: FastAPI):
logger.info("正在启动应用...")
await init_db_pool()
await init_redis_pool()
logger.info(f"CORS 允许域名: {settings.CORS_ORIGINS}")
logger.info(f"{settings.APP_NAME} 启动完成")
yield
@@ -59,10 +60,17 @@ async def access_log_middleware(request: Request, call_next):
return response
# CORS中间件 - 从环境变量读取允许的域名
# 认证中间件(先注册,后执行)
app.add_middleware(AuthMiddleware)
# CORS中间件后注册先执行- 从环境变量读取允许的域名
cors_origins = settings.CORS_ORIGINS
if not cors_origins:
logger.warning("CORS_ORIGINS 未配置或为空,跨域请求将被拒绝!请检查 .env 文件中的 CORS_ORIGINS 配置")
app.add_middleware(
CORSMiddleware,
allow_origins=settings.CORS_ORIGINS,
allow_origins=cors_origins,
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allow_headers=["*"],

View File

@@ -49,6 +49,10 @@ class AuthMiddleware(BaseHTTPMiddleware):
"""JWT认证中间件"""
async def dispatch(self, request: Request, call_next):
# OPTIONS 预检请求跳过认证
if request.method == "OPTIONS":
return await call_next(request)
path = request.url.path
# 公开路径跳过认证