这些都是好问题,而且这当然是可能的。我会告诉你我做了什么,但警告可能有更好的方法......
我使用 Vue 而不是 React,但它的构建过程还会将静态 html、js 和 css 发送到dist/
目录,因此过程应该大致相同。
首先你可以复制dist/index.html
将您提到的文件写入 FastAPItemplates/
目录。您将使用 FastAPI 路由将该文件作为模板提供。
然后将你的js和css复制到static/
目录并确保 FastAPI 了解静态和模板。
from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
@app.get("/")
async def serve_spa(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
您可能需要在 React 中设置一些内容,以便您的构建知道 js 和 css 将位于名为的目录中static
。对于 Vue 来说,有assetsDir
选项内vue.config.js
对于您关于处理不同路径的问题,例如example.com/a
and example.com/b
,这取决于您想要如何处理这些请求。您是否希望您的单个反应应用程序能够处理所有这些路线?
如果是这种情况,您可能还想查看:如何在FastAPI中捕获一条路径上的任意路径? https://stackoverflow.com/questions/63069190/how-to-capture-arbitrary-paths-at-one-route-in-fastapi/64147450
一种选择是复制serve_spa()
上面的路线并处理您的路线,例如/a
, /b
, etc.
或者使用包罗万象的路线:
@app.route("/{full_path:path}")
async def catch_all(request: Request, full_path: str):
print("full_path: "+full_path)
return templates.TemplateResponse("index.html", {"request": request})