简体   繁体   English

如何在 FastAPI 中加载 index.html

[英]How to load index.html in FastAPI

I built my app in Vue and my backend using FastAPI in Python.我在 Vue 中构建了我的应用程序,并在 Python 中使用 FastAPI 构建了我的后端。 After I did npm run build I copied the dist folder into the templates folder.在我npm run build之后,我将dist文件夹复制到templates文件夹中。 I want to load index.html but I got the error error_aborted 404 (not found) .我想加载index.html但我收到错误error_aborted 404 (not found) The static folder is inside templates folder. static文件夹位于templates文件夹内。 Why am I getting this error?为什么我会收到此错误?

from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates

app = FastAPI()

templates = Jinja2Templates(directory="templates")
app.mount("/static", StaticFiles(directory="templates"))

@app.get("/")
def serve_home(request: Request):
    return templates.TemplateResponse("index.html", context= {"request": request})

I also tried the following code, and putting the dist folder in the static folder with no templates folder.我还尝试了以下代码,并将dist文件夹放在没有templates文件夹的static文件夹中。

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

replace this:替换这个:

app.mount("/static", StaticFiles(directory="templates"))

with this:有了这个:

app.mount("/", StaticFiles(directory="templates"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM