优化静态路由

This commit is contained in:
Sakurasan
2026-07-07 16:07:10 +08:00
parent 0ba7952082
commit 62961017ea
3 changed files with 34 additions and 21 deletions
+12 -2
View File
@@ -1,7 +1,7 @@
import os
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, JSONResponse
from contextlib import asynccontextmanager
from dotenv import load_dotenv
@@ -33,6 +33,16 @@ app.include_router(shares.router, prefix="/api/share")
app.include_router(sectors.router, prefix="/api/sectors")
# 生产模式:后端同时托管前端静态文件
# catch-all 路由在 API 路由之后注册,所以 API 优先级更高
dist_path = os.path.join(os.path.dirname(__file__), "dist")
if os.path.isdir(dist_path):
app.mount("/", StaticFiles(directory=dist_path, html=True), name="static")
@app.get("/{full_path:path}")
async def serve_spa(full_path: str):
file_path = os.path.join(dist_path, full_path) if full_path else os.path.join(dist_path, "index.html")
if os.path.isfile(file_path):
return FileResponse(file_path)
# SPA fallback: 非文件路径统一返回 index.html
index_path = os.path.join(dist_path, "index.html")
if os.path.isfile(index_path):
return FileResponse(index_path, media_type="text/html")
return JSONResponse({"detail": "Not Found"}, status_code=404)