from fastapi import APIRouter from fastapi.staticfiles import StaticFiles from starlette.responses import FileResponse router = APIRouter() # 将 Vue 构建后的 dist 目录中的 assets 作为静态资源目录 #router.mount("/assets", StaticFiles(directory="frontend/dist/assets"), name="assets") @router.get("/assets/{path:path}") async def serve_static(path: str): if path.endswith(".css"): return FileResponse(f"frontend/dist/assets/{path}",media_type="text/css") elif path.endswith(".js"): return FileResponse(f"frontend/dist/assets/{path}",media_type="text/javascript") elif path.endswith(".png"): return FileResponse(f"frontend/dist/assets/{path}",media_type="image/png") else: return FileResponse(f"frontend/dist/assets/{path}") # 根路径提供 index.html @router.get("/") async def serve_vue_app(): return FileResponse("frontend/dist/index.html") # 通用路由处理,确保 history 模式下的路由正常工作 @router.get("/{full_path:path}") async def serve_vue_app_catch_all(full_path: str): return FileResponse("frontend/dist/index.html")