什么是 Vite 代理
Vite 的代理功能是基于 http-proxy-middleware 实现的,它允许开发服务器将特定的请求代理到另一个服务器。这在开发环境中非常有用,特别是当你需要:
- 解决跨域问题
- 模拟后端 API
- 代理到不同的开发/测试环境
- 处理认证和授权
基础配置
在 vite.config.js 中配置代理:
import { defineConfig } from "vite";
export default defineConfig({
server: {
proxy: {
// 将 /api 开头的请求代理到 http://localhost:3000
"/api": {
target: "http://localhost:3000",
changeOrigin: true,
},
},
},
});
代理配置选项详解
1. target
类型: string
必需: 是
说明: 目标服务器地址
'/api': {
target: 'http://localhost:3000' // 目标服务器
}
2. changeOrigin
类型: boolean
默认值: false
说明: 是否改变请求头中的 origin 字段
'/api': {
target: 'http://localhost:3000',
changeOrigin: true // 推荐设置为 true
}
3. rewrite
类型: function | object
说明: 重写请求路径
'/api': {
target: 'http://localhost:3000',
rewrite: (path) => path.replace(/^\/api/, '') // 移除 /api 前缀
}
// 或者使用对象形式
'/api': {
target: 'http://localhost:3000',
rewrite: {
'^/api': '/v1' // 将 /api 替换为 /v1
}
}
4. configure
类型: function
说明: 自定义代理配置
'/api': {
target: 'http://localhost:3000',
configure: (proxy, options) => {
proxy.on('error', (err, req, res) => {
console.log('代理错误:', err)
})
proxy.on('proxyReq', (proxyReq, req, res) => {
console.log('发送请求到目标服务器:', req.method, req.url)
})
}
}
5. headers
类型: object
说明: 添加自定义请求头
'/api': {
target: 'http://localhost:3000',
headers: {
'X-Custom-Header': 'value',
'Authorization': 'Bearer token'
}
}
6. secure
类型: boolean
默认值: true
说明: 是否验证 SSL 证书
'/api': {
target: 'https://api.example.com',
secure: false // 开发环境可以设置为 false
}
7. ws
类型: boolean
默认值: false
说明: 是否代理 WebSocket 连接
'/socket.io': {
target: 'ws://localhost:3001',
ws: true
}
8. timeout
类型: number
说明: 代理超时时间(毫秒)
'/api': {
target: 'http://localhost:3000',
timeout: 5000 // 5秒超时
}
常见问题与解决方案
问题一:跨域问题
问题描述: 即使配置了代理,仍然出现跨域错误。
解决方案:
'/api': {
target: 'http://localhost:3000',
changeOrigin: true, // 确保设置为 true
secure: false, // 如果是 HTTPS,设置为 false
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization'
}
}
问题二:WebSocket 连接问题
问题描述: WebSocket 连接无法建立。
解决方案:
'/socket.io': {
target: 'ws://localhost:3001',
ws: true, // 必须设置为 true
changeOrigin: true
}
问题三:大文件上传超时
问题描述: 上传大文件时出现超时。
解决方案:
'/upload': {
target: 'http://localhost:3000',
changeOrigin: true,
timeout: 30000, // 30秒超时
configure: (proxy, options) => {
proxy.on('proxyReq', (proxyReq, req, res) => {
// 设置更长的超时时间
proxyReq.setTimeout(30000)
})
}
}
问题四:路径重写问题
问题描述: 路径重写不生效。
解决方案:
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
// 使用函数形式确保正确重写
rewrite: (path) => {
console.log('原始路径:', path)
const newPath = path.replace(/^\/api/, '')
console.log('重写后路径:', newPath)
return newPath
}
}
总结
Vite 的代理功能为开发环境提供了强大的灵活性,能够有效解决跨域问题、模拟后端服务、处理认证等需求。通过合理配置代理,可以大大提升开发效率和调试体验。
关键要点:
- 始终设置 changeOrigin: true 解决跨域问题
- 使用 rewrite 灵活处理路径映射
- 通过 configure 实现自定义逻辑
- 合理设置超时时间和错误处理
- 根据环境动态配置代理目标
原文链接:https://code.ifrontend.net/archives/1177,转载请注明出处。
评论0