Vue 开发服务器与代理
2026/11/25大约 2 分钟
Vue 开发服务器与代理
一、为什么需要开发服务器代理
浏览器的同源策略要求协议、域名、端口一致。本地开发时,前端页面通常运行在 http://localhost:8080,后端接口运行在另一个端口或域名,直接请求会触发跨域限制。
开发服务器(dev server)在本地启动一个中间层服务器,把浏览器的请求转发给目标后端。服务器之间不受浏览器同源策略约束,因此可以绕开跨域问题。
二、Vue CLI 2.x:proxyTable
Vue CLI 2.x 在 config/index.js 的 dev 配置中使用 proxyTable,底层是 http-proxy-middleware。
module.exports = {
dev: {
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': {
target: 'http://localhost:8080/api',
secure: true,
changeOrigin: true,
pathRewrite: {
'/api': ''
}
}
},
host: '127.0.0.1',
port: '8080',
https: false,
hotOnly: false,
useEslint: true,
showEslintErrorsInOverlay: false
}
}要点:
target是后端地址,changeOrigin: true会改写请求的Host。pathRewrite用于去掉或替换路径前缀,避免后端接口多出/api。- 这是 Vue CLI 2.x 的历史写法,新项目不建议再使用。
三、Vue CLI 3.x+:devServer.proxy
Vue CLI 3.x 开始改用 devServer,配置写在 vue.config.js:
module.exports = {
devServer: {
host: 'localhost',
port: 8080,
proxy: {
'/api': {
target: 'http://localhost:3008',
changeOrigin: true,
ws: true,
pathRewrite: {
'^/api': '/'
}
}
}
}
}pathRewrite 的常见写法:
'^/api': '/':把/api/xxx重写为/xxx'^/api': '/api':保留/api前缀
四、Vite:server.proxy
Vite 使用 vite.config.js 或 vite.config.ts,代理配置在 server.proxy,底层同样基于 http-proxy:
import { defineConfig } from 'vite'
export default defineConfig({
server: {
port: 5173,
proxy: {
'/api': {
target: 'http://localhost:3008',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
}
})Vite 使用 rewrite 函数替代 pathRewrite,写法更直观。生产环境仍需由 Nginx、网关或后端配置跨域与转发,开发代理只解决本地开发问题。
五、常见问题
- 代理不生效:确认请求路径命中了
proxy的 key,且前端请求使用相对路径(如/api/user),不要写死完整后端域名。 - 代理后仍 404:检查
rewrite/pathRewrite是否把后端需要的路径前缀去掉了。 - WebSocket 代理:Vue CLI 使用
ws: true,Vite 默认支持 WebSocket 代理,必要时显式配置。 - 生产环境跨域:开发代理不是生产方案,生产应使用同源部署、网关转发或后端 CORS。
