vue cli实现反向代理
配置反向代理
在 Vue CLI 项目中,可以通过修改 vue.config.js 文件配置反向代理。假设后端 API 地址为 http://localhost:3000,需要将所有以 /api 开头的请求代理到该地址。
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
代理配置参数说明
target:指定需要代理到的目标地址。changeOrigin:修改请求头中的Host为目标地址的域名,避免跨域问题。pathRewrite:重写请求路径,例如将/api/user转换为/user。
多路径代理配置
如果需要代理多个路径到不同的目标地址,可以配置多个代理规则。
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
},
'/auth': {
target: 'http://localhost:4000',
changeOrigin: true,
pathRewrite: {
'^/auth': ''
}
}
}
}
}
环境变量配置
为了区分开发环境和生产环境的 API 地址,可以使用环境变量。在项目根目录创建 .env.development 和 .env.production 文件。
.env.development
VUE_APP_API_BASE_URL=/api
.env.production
VUE_APP_API_BASE_URL=https://production-api.com
在代码中通过 process.env.VUE_APP_API_BASE_URL 访问环境变量。
请求示例
在 Vue 组件中发起请求时,直接使用配置的代理路径。
axios.get('/api/user')
.then(response => {
console.log(response.data)
})
.catch(error => {
console.error(error)
})
注意事项
- 反向代理仅在开发环境生效,生产环境需要通过服务器(如 Nginx)配置代理。
- 修改
vue.config.js后需要重启开发服务器。







