在vite.config.ts中配置proxy后台api代理实现前台开发环境与后台生产环境对接
学习 PlayEdu 项目时,需要搭建前台代码开发环境。首先通过 git clone 下载源码,使用 VS Code 打开,并用 nvm 配置对应的 Node.js 版本:
# 下载源码 git clone --branch main https://gitee.com/playeduxyz/playedu.git playedu # 下载 nodejs 20.19.5 版本 nvm install 20.19.5# 切换到 20.19.5 版本 nvm use 20.19.5# 查看当前激活版本 nvm list# 安装项目依赖包(本项目为 React 项目) npm install# 启动开发环境 npm run dev
熟悉前端开发的同学都知道,前台代码运行时需要调用后台 API 接口。如果前台运行环境与后台 API 接口不在同一域名和端口下,会产生跨域问题,影响页面正常显示。
由于 playedu-pc 项目使用 Vite 打包 React,可以很方便地在开发环境中配置后台 API 代理,解决前后端地址不一致的问题。配置位置在 vite.config.ts 中:
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";
import gzipPlugin from "rollup-plugin-gzip";
import legacy from "@vitejs/plugin-legacy";// https://vitejs.dev/config/
export default defineConfig({server: {host: "0.0.0.0",port: 9797,// 新增后台 API 代理配置
proxy: {'/api': {target: 'http://10.2.10.180:9800',changeOrigin: true,rewrite: (path) => path.replace(/^\/api/, '/api/api')}}},plugins: [react(),legacy({targets: ["chrome 52"],additionalLegacyPolyfills: ["regenerator-runtime/runtime"],renderLegacyChunks: true,modernPolyfills: true,}),],build: {rollupOptions: {plugins: [gzipPlugin()],},},
});
其中,proxy 配置在源码中原本不存在,是开发时新增的:
// 新增后台 API 代理配置 proxy: {'/api': {target: 'http://10.2.10.180:9800',changeOrigin: true,rewrite: (path) => path.replace(/^\/api/, '/api/api')} }
因为生产环境的 API 地址格式为:http://10.2.10.180:9800/api/api/v1/course/4,所以需要添加 rewrite: (path) => path.replace(/^\/api/, '/api/api') 这段重写规则。
