Notion Blog
技术分享1 分钟阅读

FastAPI

如果你想在 FastAPI 中直接集成 React,而不做前后端分离,你可以按照以下步骤进行:

项目结构

my_project/
│── backend/               # FastAPI 相关代码
│   ├── main.py
│   ├── static/            # 静态文件 (React 编译后的文件)
│   ├── templates/         # HTML 模板文件
│── frontend/              # React 项目
│   ├── public/
│   ├── src/
│   ├── package.json
│── .gitignore
│── README.md

1. FastAPI 处理 React 静态文件

FastAPI 可以直接提供 React 编译后的静态文件。修改 main.py

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

app = FastAPI()

# 1. 挂载 React 编译后的静态文件
app.mount("/static", StaticFiles(directory="backend/static"), name="static")

# 2. 处理前端路由,返回 React 入口文件
@app.get("/{full_path:path}")
async def serve_react_app(full_path: str):
    index_path = os.path.join("static", "index.html")
    return FileResponse(index_path)

2. React 配置

frontend/package.json 中修改 build 输出目录,让 React 直接输出到 backend/static/

"scripts": {
  "start": "react-scripts start",
  "build": "react-scripts build && rm -rf ../backend/static/* && mv build/* ../backend/static/"
}


3. 构建 & 运行

构建 React
cd frontend
npm run build  # 生成静态文件并移动到 backend/static/
运行 FastAPI
uvicorn backend.main:app --host 0.0.0.0 --port 8000 --reload
访问 http://localhost:8000/,FastAPI 会返回 React 的 index.html

4. 开发时

前端开发: 运行 npm start,开发时使用 React 开发服务器。
后端开发: 运行 uvicorn,后端代码变更时自动刷新。

这样,你可以在不完全分离前后端的情况下,同时享受 React 的开发体验和 FastAPI 的后端服务。

有关使用上的问题,欢迎您在底部评论区留言,一起交流~

读者评论

评论会同步写入该文在 Notion 中的页面底部(与正文同页,便于管理)。

0/1500

暂无评论,欢迎抢沙发。