diff --git a/backend/app/main.py b/backend/app/main.py index cfe0435..1905db2 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -1,10 +1,11 @@ # app/main.py import logging import os -from fastapi.responses import FileResponse +from pathlib import Path +from fastapi.responses import FileResponse, HTMLResponse, JSONResponse import httpx from contextlib import asynccontextmanager -from fastapi import FastAPI, staticfiles +from fastapi import FastAPI, HTTPException, Request, staticfiles from fastapi.middleware.cors import CORSMiddleware from dotenv import load_dotenv @@ -112,14 +113,27 @@ app.add_middleware( # 版本控制 app.include_router(api_router, prefix="/api/v1") -# 把目录改成static对应我们放dist内容的路径就可以 -app.mount("/", staticfiles.StaticFiles(directory="app/static", html=True), name="static") - # 只需要保留API的优先匹配,catch_all可以简化成这样 @app.get("/api/{full_path:path}") async def api_not_found(full_path: str): return {"detail": "API Not Found"} +staticPath = staticfiles.StaticFiles(directory="app/static", html=True) + +# 把目录改成static对应我们放dist内容的路径就可以 +app.mount("/", staticPath, name="static") + +INDEX_HTML = Path("app/static/index.html").read_text(encoding="utf-8") + +@app.exception_handler(404) +async def not_found_handler(request: Request, exc: HTTPException): + # 如果是API路径才返回404,前端路径走catch-all不会进这里 + if request.url.path.startswith("/api/"): + return JSONResponse({"detail": "Not Found"}, status_code=404) + print("没找到") + logging.info("没找到") + return HTMLResponse(INDEX_HTML) + # 健康检查 @app.get("/", tags=["健康检查"]) async def root():