vue代理实现
Vue 代理实现方法
在 Vue 项目中,代理常用于解决跨域问题或转发 API 请求。以下是几种常见的实现方式:
开发环境代理配置(vue.config.js)
通过修改 vue.config.js 文件配置代理,适用于开发环境:
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://your-backend-server.com',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
生产环境代理方案
对于生产环境,通常需要后端服务配置反向代理(如 Nginx):

location /api {
proxy_pass http://your-backend-server.com;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
使用 axios 拦截器实现代理
可以在请求拦截器中修改请求 URL 实现类似代理效果:
import axios from 'axios';
const instance = axios.create({
baseURL: process.env.NODE_ENV === 'development' ? '/api' : 'https://production-api.com'
});
instance.interceptors.request.use(config => {
if (process.env.NODE_ENV === 'development') {
config.url = config.url.replace(/^\/api/, '');
}
return config;
});
动态代理配置
对于需要动态切换代理的场景,可以创建可配置的代理实例:

export function createProxy(baseURL) {
return axios.create({
baseURL,
withCredentials: true
});
}
// 使用示例
const proxy = createProxy('/api');
WebSocket 代理配置
如果需要代理 WebSocket 连接,可以在 vue.config.js 中配置:
devServer: {
proxy: {
'/socket': {
target: 'ws://your-websocket-server',
ws: true,
changeOrigin: true
}
}
}
多环境代理管理
结合环境变量管理不同环境的代理配置:
// .env.development
VUE_APP_API_BASE=/api
// .env.production
VUE_APP_API_BASE=https://api.example.com
// axios 配置
axios.defaults.baseURL = process.env.VUE_APP_API_BASE;
以上方法可根据实际项目需求选择使用,开发环境推荐使用 vue.config.js 配置,生产环境建议使用服务器端代理方案。






