vue3+vite+springboot路径配置:维护统一的baseUrl
提交表单:try…catch 捕获异常,如果校验失败,前台页面会有错误提示。
constsubmitForm=async()=>{try{awaitformRef.value.validate();// 校验失败会抛出异常constsubmitData={...formData};submitData.allowedSubmitTypes=submitData.allowedSubmitTypes.join(',');if(isEdit.value){awaitupdateTask(currentTaskId.value,submitData);ElMessage.success('更新成功');}else{awaitcreateTask(submitData);ElMessage.success('创建成功');}dialogVisible.value=false;taskStore.fetchTasks();}catch(error){// 如果是校验失败,error 中包含具体信息,也可以给一个通用提示ElMessage.error(error?.message||'保存失败,请检查表单填写是否正确');}};在 createTask / updateTask 的底层 axios 请求中也统一处理错误,将后端返回的错误信息抛出来。
constcreateTask=async(data)=>{try{constresponse=awaitaxios.post('/api/tasks',data);returnresponse.data;}catch(error){console.error('Create task error:',error);// 将错误抛给上层处理,以便显示提示thrownewError(error.response?.data?.message||error.message||'网络错误');}};如果后端返回的业务错误不在 HTTP 状态码体现,需要手动从 response 中读取错误信息并 throw new Error()。
【错误一】前台页面展示“Network Error”
问题分析
a. 后端服务是否正常运行
访问后端健康检查接口,http://localhost:8080/actuator/health 正常返回
b. 前端 API 基础地址正确配置
方式一: 不使用代理,直接请求完整 URL
axios 的 baseURL的设置
配置环境变量 .env.development:VITE_API_BASE_URL=http://localhost:8080/api
前端代码中使用 axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL或者直接配置
// 常见配置axios.defaults.baseURL='http://localhost:8080';该地址与后端实际运行的地址和端口一致。否则,会产生跨域问题。
同时,后端添加 CORS 配置
@ConfigurationpublicclassCorsConfig{@BeanpublicWebMvcConfigurercorsConfigurer(){returnnewWebMvcConfigurer(){@OverridepublicvoidaddCorsMappings(CorsRegistryregistry){registry.addMapping("/**").allowedOrigins("http://localhost:5173")// 前端开发服务器地址.allowedMethods("*").allowedHeaders("*").allowCredentials(true);}};}}方式二:使用 Vite,在 vite.config.js 中配置代理
exportdefault{server:{proxy:{'/api':{target:'http://localhost:8080',changeOrigin:true,rewrite:(path)=>path.replace(/^\/api/,'/api')// 保持路径}}}}- 总结
方式一、方式二,如果两者同时存在且不一致,可能导致请求重复路径。当前选择使用Vite代理。
维护统一的baseUrl采用以下组合:
前端:baseURL: ‘/api’
后端:server.servlet.context-path: /api
Controller:@RequestMapping(“/tasks”)
这样实际请求路径:前端 /api/tasks → 代理到后端 http://localhost:8080/api/tasks → 匹配 context-path=/api 和 @RequestMapping(“/tasks”)
前端统一设置 baseURL: 在 axios 封装文件utils/request.js中,设置 baseURL
// request.jsimportaxiosfrom'axios';constrequest=axios.create({baseURL:'/api',// 所有请求自动加上 /api 前缀timeout:15000,});exportdefaultrequest;后端统一设置上下文路径:配置文件 application.properties
server.servlet.context-path=/api