如何在 fastapi 中管理 Vue 路由?

问题描述 投票:0回答:1

我想在 fastapi 中提供 Vue 前端服务。

@app.get('/')
def home():
    try:
        return RedirectResponse("/index.html", status_code=303)

正确重定向并打开使用以下方式提供的 Web 应用程序:

app.mount("/", StaticFiles(directory="./static", html=True), name="static")

导航工作正常,直到打开新页面或刷新当前页面。当前端和后端链接相同时也会发生此问题。 例如,我有相同的 Vue 路由和 fastapi 路由,链接如下:

http://localhost:8000/statistics

如何在 fastapi 中管理 Vue 路由?

vuejs3 vue-router fastapi
1个回答
0
投票

您必须区分哪些端点应该返回您的 Vue 应用程序,哪些端点应该返回 API 响应。您可以通过将应用程序安装在

/api
下作为基本路径来完成此操作,然后为任何其他端点提供 vue 应用程序:

app.mount("/api", my_app)

@app.get("/{custom_path:path}")
async def serve_vue(custom_path):
    .. serve your Vue-app here

您必须这样做的原因是,当您重新加载应用程序时,浏览器会从服务器发出对

/foo/bar
的请求 - 它不知道如何提供服务,除非您已经为该服务注册了处理程序。

我建议在前端 Web 服务器(例如 nginx)内执行此操作,以便这些请求根本不会到达您的应用程序 - 这样您还可以独立于 FastAPI 应用程序构建/部署 Vue 应用程序。

© www.soinside.com 2019 - 2024. All rights reserved.