修复跨域问题

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

@@ -144,6 +144,17 @@
- header.php 注入到 JS 全局变量 - header.php 注入到 JS 全局变量
- homework.php 快捷按钮使用配置值 + 自定义输入 + ±HOMEWORK_MAX_POINTS 限制 - homework.php 快捷按钮使用配置值 + 自定义输入 + ±HOMEWORK_MAX_POINTS 限制
- attendance.php 状态按钮使用配置值 - attendance.php 状态按钮使用配置值
### 阶段 6CORS 跨域拦截修复
- [x] 6.1 注册 AuthMiddleware 为全局中间件并修复 CORS 执行顺序
【目标对象】`backend/main.py``backend/middleware/auth_middleware.py`
【修改目的】修复 CORS 跨域拦截问题AuthMiddleware 未注册导致 request.state 属性缺失,路由层 500 错误被浏览器误报为 CORS 错误
【修改方式】
- auth_middleware.py: dispatch 方法顶部添加 OPTIONS 请求跳过逻辑
- main.py: 注册 AuthMiddleware 为全局中间件先注册后执行CORS 在 Auth 之后注册(后注册先执行)
- main.py: 添加 CORS 配置启动日志和空值警告
【中间件执行顺序】CORS → Auth → access_log → 路由
【目标对象】`frontend/admin/students.php` 【目标对象】`frontend/admin/students.php`
【修改目的】除班主任角色外,隐藏家长手机号列的显示内容,保护隐私 【修改目的】除班主任角色外,隐藏家长手机号列的显示内容,保护隐私
【修改方式】在表头 HTML 和 JS 渲染处添加 `$role` 判断 【修改方式】在表头 HTML 和 JS 渲染处添加 `$role` 判断

2
.gitignore vendored
View File

@@ -41,4 +41,4 @@ Thumbs.db
*.bak *.bak
# CoStrict # CoStrict
.costrict/ .cospec/

View File

@@ -32,6 +32,7 @@ async def lifespan(app: FastAPI):
logger.info("正在启动应用...") logger.info("正在启动应用...")
await init_db_pool() await init_db_pool()
await init_redis_pool() await init_redis_pool()
logger.info(f"CORS 允许域名: {settings.CORS_ORIGINS}")
logger.info(f"{settings.APP_NAME} 启动完成") logger.info(f"{settings.APP_NAME} 启动完成")
yield yield
@@ -59,10 +60,17 @@ async def access_log_middleware(request: Request, call_next):
return response 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( app.add_middleware(
CORSMiddleware, CORSMiddleware,
allow_origins=settings.CORS_ORIGINS, allow_origins=cors_origins,
allow_credentials=True, allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"], allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allow_headers=["*"], allow_headers=["*"],

View File

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