Skip to content

Latest commit

 

History

History
149 lines (111 loc) · 3.54 KB

File metadata and controls

149 lines (111 loc) · 3.54 KB

前后端部署说明

本文档详细说明了如何部署本项目的后端(FastAPI + PostgreSQL)和前端(React)。

1. 环境准备

1.1 基础环境

  • 操作系统: Windows / Linux / macOS
  • Python: 3.8+
  • Node.js: 16+
  • PostgreSQL: 12+

1.2 后端配置

backend 目录下创建 .env 文件,配置数据库连接和其他参数:

DB_USER=iyesdo_quant
DB_PASSWORD=your_password
DB_HOST=127.0.0.1
DB_PORT=5432
DB_NAME=iyesdo_quant
SERVER_PORT=8001
JWT_SECRET_KEY=your_jwt_secret_key_here
JWT_ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30

2. 后端部署 (Backend)

2.1 安装依赖

进入 backend 目录并安装 Python 依赖:

cd backend
pip install -r requirements.txt
pip install python-dotenv

2.2 初始化数据库

首次部署或数据库地址变更后,需运行初始化脚本创建表和初始数据:

python init_db.py

成功运行后,将创建管理员账号 (admin) 和初始邀请码 (A0000)。

2.3 启动服务

使用 uvicorn 启动 FastAPI 服务:

开发模式 (热重载):

uvicorn main:app --reload --host 0.0.0.0 --port 8001

生产模式:

uvicorn main:app --host 0.0.0.0 --port 8001 --workers 4

服务启动后,API 文档地址:http://localhost:8001/docs


3. 前端部署 (Frontend)

3.1 安装依赖

进入 frontend 目录并安装 Node.js 依赖:

cd frontend
npm install

3.2 配置 API 地址

前端使用 src/config.js 管理配置。 在开发环境中,默认连接 http://localhost:8001。 在生产环境中,可以通过设置环境变量 REACT_APP_API_URL 来指定后端地址。

创建 .env 文件 (frontend/.env):

REACT_APP_API_URL=http://your-production-api-url.com

3.3 开发环境运行

启动开发服务器:

npm start

访问地址:http://localhost:3000 (或 .env 中配置的端口)

3.4 生产环境构建

构建静态文件:

npm run build

构建完成后,生成的静态文件位于 frontend/build 目录。

3.5 部署静态文件

你可以使用 Nginx、Apache 或将其集成到 FastAPI 中进行部署。

方案 A: 使用 Nginx (推荐) 配置 Nginx 指向 build 目录,并反向代理 /api 请求到后端。

关键点:必须配置 try_files $uri $uri/ /index.html;,否则刷新页面或直接访问子路由(如 /login)会出现 404 错误。

server {
    listen 80;
    server_name your_domain.com;

    location / {
        root /path/to/frontend/build;
        index index.html;
        # 必须添加这一行以支持 React Router
        try_files $uri $uri/ /index.html;
    }

    location /api {
        proxy_pass http://localhost:8001;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

详细配置参考项目根目录下的 nginx.conf.example

方案 B: 集成到 FastAPIfrontend/build 目录下的文件复制到 backend/static (或其他目录),并在 main.py 中配置静态文件服务。


4. 常见问题

  1. 数据库连接失败:

    • 检查 backend/database.py 中的配置。
    • 确保防火墙允许访问数据库端口 (5432)。
    • 确认数据库用户权限。
  2. 前端 API 请求 404:

    • 检查 Nginx 反向代理配置。
    • 确认后端服务已启动并监听正确端口。
  3. 跨域问题 (CORS):

    • 后端 main.py 已配置 CORSMiddleware,默认允许所有来源。生产环境建议限制 allow_origins