'# Ant Design Pro 配置代理
一、背景与问题
在使用 Ant Design Pro 开发中后台系统时,开发环境与生产环境的接口调用经常面临跨域问题。当前端应用与后端 API 位于不同域名时,浏览器出于安全机制会阻止跨域请求。这种场景下,配置代理成为常见的解决方案。
Ant Design Pro 作为基于 React 的中后台模板,其开发服务器默认支持代理配置。但实际开发中,开发者常遇到以下问题:
- 开发阶段代理配置不生效
- 生产环境反向代理配置错误
- 动态路由与代理配置冲突
- 跨域安全头配置遗漏
- 生产环境接口性能瓶颈
理解代理配置的底层原理和实现细节,是避免这些问题的关键。
二、基本原理
1. 开发环境代理机制
Ant Design Pro 使用的开发服务器(基于 Vite 或 Webpack)通过 http-proxy-middleware 库实现代理。其核心原理是:
- 当请求到达开发服务器时,中间件会检查请求路径是否匹配代理规则
- 匹配后,将请求转发到指定的后端地址(
target) - 通过
changeOrigin配置决定是否修改请求源 - 保留原始请求头(
Rewrite)实现身份认证和内容协商
2. 生产环境代理方案
生产环境代理主要通过以下两种方式实现:
- 反向代理服务器:使用 Nginx 或 Apache 作为反向代理,将所有请求转发到后端服务
- API 网关:在微服务架构中,通过 API 网关统一处理跨域和路由问题
三、环境准备
1. 开发环境依赖
确保项目中安装必要的依赖:
npm install http-proxy-middleware
# 或
yarn add http-proxy-middleware2. 环境配置文件
Ant Design Pro 项目结构通常包含:
├── .env
├── .env.development
├── .env.production
├── vite.config.js
├── config
│ └── proxy.js
└── src
└── main.jsx四、核心实现
1. 开发环境代理配置
在 vite.config.js 中配置代理:
// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { createProxyMiddleware } from 'http-proxy-middleware';
export default defineConfig({
plugins: [react()],
optimizeDeps: {
include: ['axios']
},
server: {
proxy: {
'/api': {
target: 'https://api.example.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
}
});关键代码解释:
changeOrigin: true:将请求源改为代理服务器地址rewrite函数:移除/api前缀,实现路径重写target:指定后端接口地址
2. 生产环境 Nginx 配置
在 /etc/nginx/sites-available/default 中配置:
server {
listen 80;
server_name your-domain.com;
location / {
proxy_pass https://api.example.com;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
}
}关键配置项:
proxy_pass:指定后端服务地址proxy_set_header:设置必要请求头proxy_http_version:兼容 WebSocket 连接
3. 动态路由代理配置
在 config/proxy.js 中实现动态路由:
// config/proxy.js
export default {
'/api': {
target: 'https://api.example.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
},
'/mock': {
target: 'https://mock-server.example.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/mock/, '')
}
};五、完整案例
1. 项目结构
├── .env
├── .env.development
├── .env.production
├── vite.config.js
├── config
│ └── proxy.js
└── src
└── main.jsx2. 开发环境配置
在 vite.config.js 中引入代理配置:
// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { createProxyMiddleware } from 'http-proxy-middleware';
export default defineConfig({
plugins: [react()],
optimizeDeps: {
include: ['axios']
},
server: {
proxy: {
'/api': {
target: 'https://api.example.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
}
});3. 前端调用示例
// src/api.js
import axios from 'axios';
const api = axios.create({
baseURL: '/api'
});
export default api;4. 生产环境部署
在 Dockerfile 中配置 Nginx 代理:
FROM nginx:latest
COPY ./nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]六、源码解析
1. Vite 代理源码
Vite 使用 http-proxy-middleware 实现代理,核心代码在 vite-node.js 中:
// node_modules/vite/dist/node/index.js
if (server.httpServer) {
const { createProxyMiddleware } = require('http-proxy-middleware');
const proxy = createProxyMiddleware({
target: 'https://api.example.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
});
server.httpServer.on('request', (req, res) => {
const proxyReq = new ProxyRequest(req, res);
proxyReq.on('error', (err) => {
console.error('Proxy error:', err);
});
proxyReq.on('proxyRes', (proxyRes, req, res) => {
// 处理响应
});
});
}2. Nginx 代理源码
Nginx 通过 ngx_http_proxy_module 实现代理功能,核心配置项包括:
proxy_pass:指定后端服务地址proxy_set_header:设置请求头proxy_http_version:设置 HTTP 协议版本
七、进阶使用
1. 动态代理配置
在 config/proxy.js 中实现动态配置:
// config/proxy.js
export default {
[process.env.VITE_API_BASE]: {
target: 'https://api.example.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
},
[process.env.VITE_MOCK_BASE]: {
target: 'https://mock-server.example.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/mock/, '')
}
};2. 高级配置项
// vite.config.js
server: {
proxy: {
'/api': {
target: 'https://api.example.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
secure: false, // 允许 HTTPS 证书不合法
logLevel: 'debug' // 开启调试日志
}
}
}八、性能与工程实践
1. 性能优化
- 缓存策略:在 Nginx 中配置
proxy_cache缓存静态资源 - 连接复用:设置
keepalive_timeout保持连接 - 限流控制:使用
limit_req防止 DDoS 攻击
2. 安全防护
- CORS 配置:在 Nginx 中设置
add_header控制跨域 - 安全头:设置
X-Content-Type-Options、X-Frame-Options等安全头 - 请求验证:在后端服务中校验请求来源
3. 异常处理
// vite.config.js
server: {
proxy: {
'/api': {
target: 'https://api.example.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
onError: (err, req, res) => {
console.error('Proxy error:', err);
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Proxy error' }));
}
}
}
}九、常见问题与踩坑
1. 常见错误
| 问题 | 原因 | 解决方案 |
|---|---|---|
| 代理不生效 | 配置文件格式错误 | 检查 JSON 语法 |
| 路径匹配失败 | 正则表达式错误 | 使用 ^/api 精确匹配 |
| 生产环境 404 | 未配置反向代理 | 检查 Nginx 配置 |
| 跨域安全头缺失 | 未设置 Access-Control-Allow-Origin | 在 Nginx 中添加头 |
2. 常见坑点
- 开发环境代理仅限于开发服务器:生产环境需配置反向代理
- 动态路由匹配问题:需使用正则表达式精确匹配
- SSL 证书问题:生产环境需配置
secure: false或ssl_verify选项 - 路径重写错误:需确保
rewrite函数正确处理路径
十、最佳实践
1. 开发环境配置建议
- 使用
/api作为统一前缀 - 配置
rewrite去除前缀 - 设置
changeOrigin: true保持源地址 - 开启调试日志便于排查问题
2. 生产环境配置建议
- 使用 Nginx 或 Apache 作为反向代理
- 配置安全头和限流策略
- 使用
proxy_cache缓存静态资源 - 配置
keepalive_timeout提升性能
3. 推荐的目录结构
├── config
│ └── proxy.js
├── src
│ └── api.js
├── .env
├── .env.development
├── .env.production
└── vite.config.js十一、总结
Ant Design Pro 的代理配置是解决跨域问题的关键技术,其核心原理在于开发服务器的代理中间件和生产环境的反向代理配置。通过深入理解其工作原理,我们可以更好地应对开发中的各种场景。
在实际开发中,开发环境建议使用 /api 前缀配合 rewrite 路径重写,生产环境推荐使用 Nginx 或 Apache 实现反向代理。同时,需要注意安全头配置和性能优化,避免常见错误。
通过合理配置代理,我们可以确保前后端接口的稳定通信,同时提升开发效率和生产环境的性能表现。在遇到代理问题时,应优先检查配置文件、日志输出和网络请求,逐步排查问题根源。