Skip to content

同时运行前后端

全栈开发
大多数项目都需要同时运行前端和后端服务。本指南教你如何高效地管理两个服务。

📋 前置要求

前端和后端代码都已下载
相关环境已安装(Node.js/Java/Python)
两边的依赖都已安装

🚀 方式一:使用两个终端(推荐新手)

这是最简单直观的方式。

步骤

终端 1 - 启动后端:

bash
        $
        cd backend && pnpm run start:dev
      

终端 2 - 启动前端:

bash
        $
        cd frontend && pnpm run dev
      
优点
- 简单直观 - 可以分别查看两边的日志 - 出错容易定位

🚀 方式二:使用 concurrently

在根目录同时启动两个服务。

安装

bash
        $
        pnpm add -D concurrently
      

配置 package.json

在根目录的 package.json 添加脚本:

json
{
  "scripts": {
    "dev": "concurrently \"pnpm --filter backend run start:dev\" \"pnpm --filter frontend run dev\"",
    "dev:backend": "pnpm --filter backend run start:dev",
    "dev:frontend": "pnpm --filter frontend run dev"
  }
}

运行

bash
        $
        pnpm run dev
      

🚀 方式三:使用 Docker Compose

如果项目配置了 Docker,可以一键启动所有服务。

docker-compose.yml 示例

yaml
version: '3.8'
services:
  backend:
    build: ./backend
    ports:
      - "3000:3000"
    environment:
      - DATABASE_URL=postgresql://postgres:password@db:5432/app
    depends_on:
      - db

  frontend:
    build: ./frontend
    ports:
      - "5173:5173"
    depends_on:
      - backend

  db:
    image: postgres:15
    environment:
      POSTGRES_PASSWORD: password
      POSTGRES_DB: app
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  pgdata:

运行

bash
        $
        docker-compose up -d
      

查看日志:

bash
        $
        docker-compose logs -f
      

🔌 前后端如何连接

前端通过 API 请求与后端通信。

1. 配置前端 API 地址

在前端项目的 .env 文件中配置:

VITE_API_URL=http://localhost:3000

2. 确保后端 CORS 已配置

后端需要允许前端地址的跨域请求。

NestJS:

typescript
app.enableCors({
  origin: 'http://localhost:5173'
});

Express:

javascript
app.use(cors({
  origin: 'http://localhost:5173'
}));

✅ 验证连接

检查后端

bash
        $
        curl http://localhost:3000/health
      

应该返回类似 {"status":"ok"} 的响应。

检查前端 API 调用

  1. 打开浏览器开发者工具(F12)
  2. 切换到 Network 面板
  3. 操作页面触发 API 请求
  4. 检查请求是否成功

🔧 开发技巧

使用代理避免 CORS

在前端 vite.config.ts 中配置代理:

typescript
export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  }
})

这样前端请求 /api/users 会自动代理到 http://localhost:3000/users

使用环境变量区分环境

.env.development:

VITE_API_URL=http://localhost:3000

.env.production:

VITE_API_URL=https://api.your-domain.com

❓ 常见问题

CORS 错误

Access to XMLHttpRequest at 'http://localhost:3000/api' 
from origin 'http://localhost:5173' has been blocked by CORS policy

解决方法:

  1. 后端配置 CORS(见上方)
  2. 或使用前端代理(见上方)

端口冲突

如果端口被占用,可以修改:

后端(NestJS/.env):

PORT=3001

前端(vite.config.ts):

typescript
server: {
  port: 5174
}

API 请求超时

  1. 确认后端服务正在运行
  2. 检查 API 地址是否正确
  3. 查看后端日志是否有错误

📊 服务端口总览

服务默认端口用途
前端开发服务器5173Vite 开发服务器
NestJS 后端3000API 服务
Spring Boot 后端8080API 服务
FastAPI/Django 后端8000API 服务
PostgreSQL5432数据库
MySQL3306数据库

⏭️ 下一步

项目运行成功后:

Released under the MIT License.