Vite React项目BookAppointment.jsx调用后端预约接口出现404错误
问题背景
在React+Vite项目中,BookAppointment.jsx组件调用/backend/appointment/create接口时返回404 (Not Found),但Appointments.jsx组件调用同一接口却完全正常。已通过Insomnia测试后端接口,确认接口本身可正常创建预约。前端运行在http://localhost:5173,后端运行在http://localhost:3000,Vite已配置代理规则。
解决方案
1. 修正Vite代理的路径重写规则
当前Vite代理仅转发请求,未移除/backend前缀,导致实际转发到后端的路径为http://localhost:3000/backend/appointment/create。若后端接口实际路径为/appointment/create(无/backend前缀),则会返回404。
修改vite.config.js,添加路径重写逻辑:
// vite.config.js import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react-swc'; export default defineConfig({ plugins: [react()], server: { proxy: { '/backend': { target: 'http://localhost:3000', secure: false, rewrite: (path) => path.replace(/^\/backend/, '') // 移除请求路径中的/backend前缀 }, }, }, });
2. 对齐请求数据结构与后端要求
对比两个组件的请求数据,BookAppointment.jsx的appointmentData缺少后端接口要求的必填字段,且数据结构与Appointments.jsx差异较大。部分后端框架在参数校验不通过时会错误返回404(而非标准的400)。
调整BookAppointment.jsx的请求数据,对齐Appointments.jsx的结构:
const handleStep3Submit = async (e) => { e.preventDefault(); try { // 从上下文/状态中获取当前登录用户信息 const currentUser = /* 补充获取currentUser的逻辑 */; const appointmentData = { // 补充后端要求的必填字段 schedule: /* 从组件状态中获取预约日期 */, technicianName: /* 从组件状态中获取技师名称 */, firstName: currentUser.firstName, lastName: currentUser.lastName, phone: /* 从表单或用户信息中获取手机号 */, email: currentUser.email, services: selectedServices, address: e.target.address.value, landmark: e.target.landmark.value, // 按后端要求包装patient数组 patient: [{ typeOfAnimal: selectedAnimalType, numberOfHeads: e.target.numberOfHeads.value, age: e.target.age.value, }], }; const response = await fetch('/backend/appointment/create', { method: 'POST', headers: { 'Content-Type': 'application/json', // 若后端需要认证,添加令牌头 'Authorization': `Bearer ${currentUser.token}` }, body: JSON.stringify(appointmentData), }); if (response.ok) { navigate('/dashboard'); } else { // 打印后端返回的完整错误信息,便于排查 console.error('Error creating appointment:', await response.text()); } } catch (err) { console.error('Step 3 Form Submission Error:', err); } };
3. 检查请求头的认证信息
若后端接口需要登录认证,BookAppointment.jsx的请求可能未携带认证令牌(如JWT),导致后端拒绝访问并返回404。确保请求头包含与Appointments.jsx一致的认证信息。
4. 查看后端请求日志
直接查看后端的请求日志,确认收到的请求路径、参数、头信息是否符合预期,这是定位问题最直接的方式。重点检查:
- 请求路径是否匹配后端接口路由
- 请求体的结构和字段是否完整
- 是否携带了必要的认证头
内容的提问来源于stack exchange,提问作者Jays

