Vite Proxy配置详解:从入门到实战应用
Vite Proxy配置详解:从入门到实战应用
一、什么是Proxy代理?
Proxy(代理)是开发中常用的解决跨域问题的方案。Vite内置了基于http-proxy
的代理功能,可以轻松配置API请求转发。
二、基础配置
在vite.config.js
中配置proxy选项:
export default defineConfig({server: {proxy: {/api: {target: http://localhost:3000,changeOrigin: true,rewrite: path => path.replace(/^\/api/, )}}}
})
target
: 代理目标地址changeOrigin
: 修改请求头中的host为目标URLrewrite
: 路径重写
三、进阶配置
1. 多代理配置
proxy: {/api1: {target: http://localhost:3001,// ...其他配置},/api2: {target: http://localhost:3002,// ...其他配置}
}
2. WebSocket代理
proxy: {/socket.io: {target: ws://localhost:3000,ws: true}
}
3. 自定义代理规则
proxy: {^/api/.*: {target: http://localhost:3000,bypass(req) {if (req.headers.accept.indexOf(html) !== -1) {return /index.html}}}
}
四、实战应用
1. 解决开发环境跨域
proxy: {/api: {target: https://production-server.com,changeOrigin: true,secure: false}
}
2. 模拟不同环境API
const targetMap = {dev: http://dev-server,test: http://test-server,prod: https://prod-server
}proxy: {/api: {target: targetMap[process.env.NODE_ENV],changeOrigin: true}
}
五、常见问题
- 代理不生效:检查路径是否匹配,特别是正则表达式
- HTTPS证书问题:设置
secure: false
跳过证书验证 - WebSocket无法连接:确保设置了
ws: true
六、总结
Vite的Proxy配置简单强大,能有效解决开发中的跨域问题。通过灵活配置可以满足各种复杂场景需求。
提示:生产环境应使用Nginx等服务器处理代理,Vite代理仅用于开发环境。