You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI部署Vue.js模板时/api接口404问题求助

问题原因

你遇到的404错误是因为静态文件挂载的优先级高于FastAPI的路由。当你使用app.mount("/", StaticFiles(...))时,所有根路径下的请求(包括/api)都会先被StaticFiles处理,而它找不到对应静态资源,就直接返回404了,FastAPI的/api路由根本没机会被执行。

解决方案

不需要像Node.js那样分开服务器,只需要调整静态文件的挂载策略或者路由顺序即可,以下是两种可行方案:

方案一:给静态文件设置子路径挂载

把静态文件挂载到非根路径,比如/static,同时调整Vue项目的配置,让静态资源请求都指向这个路径,然后保留根路径的路由给FastAPI处理:

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
import uvicorn

app = FastAPI()
# 挂载静态文件到/static路径
app.mount("/static", StaticFiles(directory="./front/static"), name="static")

@app.get("/")
async def root():
    return FileResponse("./front/index.html", media_type="text/html")

@app.get("/api")
async def api():
    return {"Fastapi with web": "Hello"}

if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8080, reload=True)

注意:需要修改Vue项目的vue.config.js,设置publicPath: "/static",确保打包后的资源路径正确。

方案二:调整挂载顺序,适配SPA路由

如果想保持根路径挂载静态文件,需要先注册FastAPI的路由,再挂载StaticFiles,这样FastAPI会优先处理已定义的路由,剩下的请求交给StaticFiles处理(适合Vue单页应用的路由跳转):

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
import uvicorn

app = FastAPI()

# 先注册所有API路由
@app.get("/api")
async def api():
    return {"Fastapi with web": "Hello"}

# 再挂载静态文件到根路径,html=True会处理SPA的路由跳转
app.mount("/", StaticFiles(directory="./front/", html=True), name="static")

if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8080, reload=True)

这种方案不需要修改Vue的配置,所有未匹配到API路由的请求都会返回index.html,由Vue的前端路由处理。

补充说明

Node.js(Express)中通常是先定义API路由,再使用express.static处理静态文件,所以API路由会优先被匹配,这就是你用Express能正常运行的原因。FastAPI的挂载逻辑和Express类似,只是你之前的代码把静态文件挂载放在了路由注册前面,导致了优先级问题。

内容的提问来源于stack exchange,提问作者Joel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 23:55:32