Vue 开发环境配置:使用 devServer.proxy 解决跨域问题
引言
在现代 Web 开发中,前端和后端通常独立开发,前端运行在 http://localhost:8080
,而后端可能运行在 http://localhost:8000
或其他端口。由于浏览器的 同源策略(Same-Origin Policy),直接请求不同源的 API 会导致 跨域(CORS)错误。
Vue CLI 提供了 devServer.proxy
配置,可以在开发环境下轻松设置反向代理,让前端请求无缝转发到后端服务器,避免跨域问题。
本文将详细介绍如何在 vue.config.js
中配置代理,并提供实际案例和常见问题解决方案。
1. 为什么需要配置代理?
跨域问题的产生
- 前端运行在
http://localhost:8080
(Vue DevServer)。 - 后端运行在
http://localhost:8000
(如 Django、Spring Boot、Node.js)。 - 浏览器限制跨域请求,导致 API 调用失败。
解决方案
- 后端设置 CORS 头(如
Access-Control-Allow-Origin
)。 - 前端配置代理(推荐,开发阶段更方便)。
Vue CLI 的 devServer.proxy
可以:
- 将
/api
请求转发到后端服务器。 - 修改请求头,绕过浏览器限制。
- 支持 WebSocket、HTTPS 等高级代理。
2. 配置 vue.config.js
代理
基本代理配置
// vue.config.js
module.exports = {devServer: {proxy: {// 代理所有以 `/api` 开头的请求'/api': {target: 'http://localhost:8000', // 后端服务器地址changeOrigin: true, // 修改请求头 HostpathRewrite: {'^/api': '', // 移除 `/api` 前缀},},},},
};
配置说明
配置项 | 说明 |
---|---|
target | 后端服务器地址(如 http://localhost:8000 )。 |
changeOrigin | 是否修改请求头 Host (通常设为 true )。 |
pathRewrite | 重写请求路径(如去掉 /api 前缀)。 |
ws | 是否代理 WebSocket(默认 true )。 |
secure | 是否验证 HTTPS 证书(默认 true )。 |
3. 实际案例
(1) 代理单一 API 路径
// vue.config.js
module.exports = {devServer: {proxy: {'/api': {target: 'http://localhost:8000',changeOrigin: true,},},},
};
- 前端请求:
http://localhost:8080/api/users
- 实际请求:
http://localhost:8000/api/users
(2) 代理多个后端服务
// vue.config.js
module.exports = {devServer: {proxy: {'/api': {target: 'http://localhost:8000',changeOrigin: true,},'/auth': {target: 'http://localhost:8001',changeOrigin: true,},},},
};
/api
→http://localhost:8000
/auth
→http://localhost:8001
(3) 重写路径(去掉前缀)
// vue.config.js
module.exports = {devServer: {proxy: {'/api': {target: 'http://localhost:8000',changeOrigin: true,pathRewrite: {'^/api': '', // 去掉 `/api` 前缀},},},},
};
- 前端请求:
http://localhost:8080/api/users
- 实际请求:
http://localhost:8000/users
(/api
被移除)
4. 常见问题
(1) 代理不生效
✅ 检查步骤:
-
target
是否正确:确保后端服务器正在运行。 - 请求路径是否匹配:前端代码是否以
/api
开头。 - 重启 DevServer:修改
vue.config.js
后需重启npm run serve
。
(2) 代理 WebSocket
// vue.config.js
module.exports = {devServer: {proxy: {'/socket': {target: 'ws://localhost:8000',ws: true, // 启用 WebSocket 代理},},},
};
(3) 代理 HTTPS 接口
// vue.config.js
module.exports = {devServer: {proxy: {'/api': {target: 'https://your-backend.com',secure: false, // 忽略 HTTPS 证书验证},},},
};
5. 完整配置示例
// vue.config.js
module.exports = {devServer: {port: 8080, // 前端开发服务器端口open: true, // 启动后自动打开浏览器proxy: {// 代理 API 请求'/api': {target: 'http://localhost:8000',changeOrigin: true,pathRewrite: { '^/api': '' },},// 代理静态资源'/static': {target: 'http://localhost:8000',changeOrigin: true,},// 代理 WebSocket'/socket': {target: 'ws://localhost:8000',ws: true,},},},
};
6. 总结
场景 | 配置方式 |
---|---|
基本代理 | proxy: { '/api': { target: '...' } } |
路径重写 | pathRewrite: { '^/api': '' } |
多路径代理 | 配置多个 proxy 条目 |
WebSocket | ws: true |
HTTPS | secure: false |
通过 devServer.proxy
,你可以轻松解决开发环境下的跨域问题,让前端请求无缝对接后端 API!