vue项目proxy代理的方式
以下是一个详细的 Vue 项目配置 Proxy 代理 的示例和说明,用于解决开发环境跨域问题:
1. 基础代理配置
vue.config.js 配置文件
// vue.config.js
module.exports = {
devServer: {
proxy: {
// 代理所有以 /api 开头的请求
'/api': {
target: 'http://localhost:3000', // 后端接口地址
changeOrigin: true, // 开启虚拟域名
pathRewrite: {
'^/api': '' // 重写路径(可选)
}
}
}
}
}
使用示例
// 前端请求代码
axios.get('/api/users') // 实际转发到 http://localhost:3000/users
2. 多路径代理配置
// vue.config.js
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true
},
'/uploads': {
target: 'http://resource-server.com',
changeOrigin: true,
pathRewrite: {
'^/uploads': '/static' // 重写路径到/static
}
}
}
}
}
3. 高级代理配置
代理 WebSocket
// vue.config.js
module.exports = {
devServer: {
proxy: {
'/socket.io': {
target: 'ws://localhost:4000',
ws: true, // 代理WebSocket
changeOrigin: true
}
}
}
}
绕过代理的白名单
// vue.config.js
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
bypass: function(req) {
// 不代理 /api/login 请求
if (req.url === '/api/login') {
return req.url;
}
}
}
}
}
}
4. 配置参数说明
参数 | 作用 |
---|---|
target | 代理的目标服务器地址 (必须配置) |
changeOrigin | 将请求头中的host设置为目标地址 (默认false,建议设为true) |
pathRewrite | 路径重写规则 (支持正则表达式) |
ws | 是否代理WebSocket (默认跟随主配置) |
headers | 自定义请求头 (如添加认证信息) |
5. 常见问题排查
代理不生效的检查步骤
- 检查
vue.config.js
是否在项目根目录 - 重启开发服务器 (
npm run serve
) - 查看浏览器控制台网络请求:
- 请求URL应为相对路径 (如
/api/data
) - 实际请求地址应显示为代理目标地址
- 请求URL应为相对路径 (如
- 检查是否配置了多层路径重写
生产环境注意事项
- 该配置 仅适用于开发环境 (
npm run serve
) - 生产环境需要通过Nginx等Web服务器配置反向代理
- 推荐生产环境使用绝对路径接口地址
完整配置示例
// vue.config.js
module.exports = {
devServer: {
proxy: {
// 用户服务接口
'/user-api': {
target: 'http://user-service:8000',
changeOrigin: true,
pathRewrite: {
'^/user-api': '/api/v1'
}
},
// 订单服务接口
'/order-api': {
target: 'http://order-service:8001',
changeOrigin: true,
pathRewrite: {
'^/order-api': '/api/v2'
}
},
// 文件上传服务
'/upload': {
target: 'http://file-service:8002',
changeOrigin: true
}
}
}
}
Nginx 生产环境配置参考
server {
listen 80;
server_name yourdomain.com;
location /api/ {
proxy_pass http://backend-server:3000/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
location / {
root /usr/share/nginx/html;
try_files $uri $uri/ /index.html;
}
}
通过以上配置,即可实现开发环境的接口代理和跨域请求处理。