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

Vue3 + Vite 项目中 API 代理配置问题分析与解决

问题背景

在开发一个基于 Vue3 + Vite + Spring Boot 的前后端分离项目时,遇到了一个典型的 API 代理配置问题。前端在访问用户信息接口时出现 404 错误,具体表现为:

GET http://localhost:3000/api/user/current 404 (Not Found)

错误现象

控制台错误信息

请求错误: AxiosError
- message: 'Request failed with status code 404'
- name: 'AxiosError' 
- code: 'ERR_BAD_REQUEST'

错误调用栈

(匿名) at UserPage.vue:43
Promise.then at main.ts:22

问题分析

1. 项目架构分析

前端配置:

  • 运行端口:3000
  • 使用 Vite 开发服务器
  • 配置了 API 代理到后端

后端配置:

  • 运行端口:8080
  • Spring Boot 应用
  • 设置了 context-path: /api
  • 控制器映射:@RequestMapping("/user")

2. 原始配置问题

Vite 代理配置(错误版本):

// vite.config.ts
export default defineConfig({server: {port: 3000,proxy: {'/api': {target: 'http://localhost:8080',changeOrigin: true,secure: false,rewrite: (path) => path.replace(/^\/api/, ''), // ❌ 问题所在},},},
});

问题分析:

  1. 前端请求:/api/user/current
  2. Vite 代理移除 /api 前缀后:/user/current
  3. 转发到后端:http://localhost:8080/user/current
  4. 但后端期望的路径:http://localhost:8080/api/user/current

路径不匹配:

  • 前端实际请求:/user/current
  • 后端期望路径:/api/user/current
  • 结果:404 Not Found

解决方案

1. 修改 Vite 代理配置

正确的配置:

// vite.config.ts
export default defineConfig({server: {port: 3000,proxy: {'/api': {target: 'http://localhost:8080',changeOrigin: true,secure: false,// ✅ 注释掉 rewrite,保持 /api 前缀// rewrite: (path) => path.replace(/^\/api/, ''),},},},
});

2. 请求流程对比

修改前:

前端请求: /api/user/current
↓ (移除 /api 前缀)
代理转发: http://localhost:8080/user/current
↓
后端接收: /user/current ❌ (404)

修改后:

前端请求: /api/user/current
↓ (保持 /api 前缀)
代理转发: http://localhost:8080/api/user/current
↓
后端接收: /api/user/current ✅ (200)

验证过程

1. 检查服务状态

# 检查后端端口
netstat -ano | findstr :8080
# 输出: TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING 11460# 检查前端端口  
netstat -ano | findstr :3000
# 输出: TCP 0.0.0.0:3000 0.0.0.0:0 LISTENING 44124

2. 直接测试后端 API

curl -v http://localhost:8080/api/user/current
# 响应: HTTP/1.1 200
# 返回: {"code":40100,"data":null,"message":"未登录"}

3. 测试前端代理

curl -v http://localhost:3000/api/user/current
# 响应: HTTP/1.1 200 OK
# 返回: {"code":40100,"data":null,"message":"未登录"}

技术要点总结

1. Vite 代理配置原则

  • 保持路径一致性:代理配置要与后端路由配置保持一致
  • 理解上下文路径:后端设置的 context-path 会影响完整路径
  • 调试技巧:使用 curl 命令直接测试 API 接口

2. Spring Boot 上下文路径

# application.yml
server:servlet:context-path: /api  # 所有接口都会加上 /api 前缀

3. 前后端路径映射关系

前端请求路径: /api/user/current
↓
Vite 代理: 转发到 http://localhost:8080/api/user/current
↓
Spring Boot: 匹配 @RequestMapping("/user") + @GetMapping("/current")
↓
最终路径: /api/user/current ✅

常见陷阱

1. 路径重写陷阱

// ❌ 错误:移除了必要的路径前缀
rewrite: (path) => path.replace(/^\/api/, '')// ✅ 正确:保持路径完整性
// 注释掉 rewrite 或根据实际需求配置

2. 端口配置陷阱

// ❌ 错误:target 端口不匹配
target: 'http://localhost:3000'  // 应该是后端端口// ✅ 正确:指向后端服务端口
target: 'http://localhost:8080'

3. 跨域配置陷阱

// ✅ 必要的跨域配置
changeOrigin: true,
secure: false,

实践

1. 环境配置分离

// config/env.ts
export const ENV_CONFIG = {API_BASE_URL: '/api',DEBUG: import.meta.env.DEV,
};

2. 统一错误处理

// plugins/myAxios.ts
myAxios.interceptors.response.use((response) => response,(error) => {if (ENV_CONFIG.DEBUG) {console.error('请求错误:', error);}return Promise.reject(error);}
);

3. 开发调试技巧

  • 使用浏览器开发者工具查看网络请求
  • 使用 curl 命令直接测试 API
  • 检查服务端口占用情况
  • 查看后端日志确认请求是否到达

总结

这个问题的核心在于理解前后端分离架构中的路径映射关系。Vite 的代理配置需要与后端的路由配置保持一致,特别是当后端设置了上下文路径时。

关键要点:

  1. 理解 Spring Boot 的 context-path 配置
  2. 正确配置 Vite 代理的路径重写规则
  3. 使用调试工具验证配置正确性
  4. 建立完整的请求流程验证机制

通过这次问题的解决,我们不仅修复了当前的错误,更重要的是建立了对前后端分离架构中路径映射的深入理解,为后续的开发工作奠定了良好的基础。


标签: #Vue3 #Vite #SpringBoot #API代理 #前后端分离 #问题排查

http://www.dtcms.com/a/310384.html

相关文章:

  • 如何处理Y2K38问题
  • 驾驶场景安全带识别误检率↓76%:陌讯动态特征聚合算法实战解析
  • 【深度学习①】 | Numpy数组篇
  • 【从0开始学习Java | 第12篇】内部类
  • C语言:冒泡排序
  • VUE:学习路径
  • 机器学习:开启智能时代的钥匙
  • 前端学习日记(十七)
  • Unity3D制作UI动画效果
  • treeshaking,webpack,vite
  • 技术为核,口碑为盾:普瑞眼科成都市场“卷王”地位的形成逻辑
  • Canny边缘检测算法-个人记录
  • 计数组合学7.10(舒尔函数的组合定义)
  • 图片搜索1688的商品技术实现:API接口item_search_img
  • 嵌入式——C语言:俄罗斯方块
  • C#常见的转义字符
  • 国产开源大模型崛起:使用Kimi K2/Qwen2/GLM-4.5搭建编程助手
  • 浏览器渲染过程
  • VSCode Python 与 C++ 联合调试配置指南
  • web前端第一次作业
  • TwinCAT3编程入门2
  • 如何快速给PDF加书签--保姆级教程
  • TCP协议的特点和首部格式
  • 电力系统与变压器实验知识全总结 | 有功无功、同步发电机、短路空载实验、电压调整率、效率条件全讲透!
  • curl命令使用
  • 蒙特卡罗方法(Monte Carlo Method)_学习笔记
  • 【面板数据】全国31省名义、实际GDP及GDP平减指数数据(2000-2024年)
  • VR拍摄的流程与商业应用,实用的VR拍摄技巧
  • 汇川ITS7100E触摸屏交互界面开发(二)界面开发软件使用记录
  • python试卷01