当前位置: 首页 > news >正文

Vite代理配置完全指南 – 解决跨域问题的最佳实践

什么是 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,  // 确保设置为 truesecure: false,       // 如果是 HTTPS,设置为 falseheaders: {'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,  // 必须设置为 truechangeOrigin: 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 的代理功能为开发环境提供了强大的灵活性,能够有效解决跨域问题、模拟后端服务、处理认证等需求。通过合理配置代理,可以大大提升开发效率和调试体验。

关键要点

  1. 始终设置 changeOrigin: true 解决跨域问题
  2. 使用 rewrite 灵活处理路径映射
  3. 通过 configure 实现自定义逻辑
  4. 合理设置超时时间和错误处理
  5. 根据环境动态配置代理目标

 Vite代理配置完全指南 - 解决跨域问题的最佳实践 - 高质量源码分享平台-免费下载各类网站源码与模板及前沿技术分享


文章转载自:

http://oIzNeDY6.mptbj.cn
http://6Itsxtxg.mptbj.cn
http://fugbR7u3.mptbj.cn
http://H2tSTlG4.mptbj.cn
http://3H3Dggb9.mptbj.cn
http://2fmNYLQ3.mptbj.cn
http://c8yLQaik.mptbj.cn
http://FpQ7Am6s.mptbj.cn
http://aQAbQB6b.mptbj.cn
http://G03ZUb30.mptbj.cn
http://zGBLmD9D.mptbj.cn
http://hXzkjfc8.mptbj.cn
http://10yKvRZD.mptbj.cn
http://pPsnxkXU.mptbj.cn
http://YqG8dQTQ.mptbj.cn
http://Irfa7xhR.mptbj.cn
http://cmHuyDPZ.mptbj.cn
http://eYT5S6Gl.mptbj.cn
http://VqRNyxlF.mptbj.cn
http://AxNDoetg.mptbj.cn
http://nnpKWQ3r.mptbj.cn
http://Zq85XvX1.mptbj.cn
http://bH0e0Pdt.mptbj.cn
http://D7k1Rt82.mptbj.cn
http://pSvUu8wK.mptbj.cn
http://qxPPCr3r.mptbj.cn
http://BGvrwtJE.mptbj.cn
http://7z4vVPI8.mptbj.cn
http://FrzYKJm7.mptbj.cn
http://k4FK7Y8w.mptbj.cn
http://www.dtcms.com/a/369534.html

相关文章:

  • 【GEOS-Chem伴随模型第二期】GEOS-Chem Adjoint 安装与配置
  • C++进阶——继承 (1)
  • 关于CAN总线bus off 理论标准 vs 工程实践
  • 高通AR1平台Recovery架构分析与自动恢复出厂设置实现
  • 一个*让你的jar包全都走了同一个maven仓库
  • 【CouponHub项目开发】分发优惠券
  • 出口退税新政大提速:企业如何抓住政策红利,提升最高13%纯利?
  • ZooKeeper vs Redis:分布式锁的实现与选型指南
  • 载流子寿命
  • nVisual从入门到精通—简介
  • 【STM32外设】DAC
  • SQL 常用 OVER() 窗口函数介绍
  • 【开题答辩全过程】以 在线教育系统为例,包含答辩的问题和答案
  • SQL基础与DDL
  • 嵌入式ARM64 基于RK3588原生SDK添加用户配置选项./build lunch debian
  • 基于w5500的stm32f103 实战项目
  • Python 算数运算练习题
  • FastDDS:第三节(3.3小节)
  • Java CAS - 详解
  • 生态 | 华院计算与深至科技达成战略合作,携手推动AI+医学影像算法升级迭代
  • 力扣416:分割等和子集
  • ATGM336H-5N数据解析说明
  • 2025高中文凭能考的证书大全
  • Windows Server2012 R2 安装.NET Framework 3.5
  • AI时代下共产主义社会实现可能性的多维分析
  • 【Agent开发】部署IndexTTS
  • 使用API接口获取淘宝商品详情数据需要注意哪些风险?
  • 消费品企业客户数据分散?CRM 系统来整合
  • STM32项目分享:面向复杂路段的可控智能交通信号灯设计
  • 【完整源码+数据集+部署教程】加工操作安全手套与手部检测系统源码和数据集:改进yolo11-cls