在 Vue 3 中解析 Spring Boot 返回的 ResponseEntity
主要涉及处理 HTTP 响应。Spring Boot 的 ResponseEntity
通常包含状态码、响应头和响应体(JSON 数据为主)。以下是详细步骤和代码示例:
解决方案步骤:
发送 HTTP 请求:使用
axios
或fetch
调用 Spring Boot API处理响应:解析 JSON 响应体,获取状态码和头信息
处理异常:捕获可能的网络错误或 API 错误状态码
更新 Vue 状态:将解析后的数据绑定到 Vue 组件
完整示例代码
1. 安装依赖
bash
复制
下载
npm install axios
2. Vue 组件示例
vue
复制
下载
<template> <div> <button @click="fetchData">获取数据</button> <div v-if="loading">加载中...</div> <div v-if="error">{{ error }}</div> <div v-if="data"> <h3>响应数据:</h3> <pre>{{ data }}</pre> <p>状态码:{{ status }}</p> </div> </div> </template> <script> import axios from 'axios'; export default { data() { return { loading: false, error: null, data: null, status: null }; }, methods: { async fetchData() { this.loading = true; this.error = null; try { // 替换为你的 Spring Boot API 地址 const response = await axios.get('http://localhost:8080/api/data', { headers: { // 如果需要认证 // 'Authorization': 'Bearer your_token' } }); // 解析 ResponseEntity this.status = response.status; // HTTP 状态码 this.data = response.data; // 响应体(Spring Boot 返回的 body 部分) // 如果需要访问响应头 const contentType = response.headers['content-type']; console.log('Content-Type:', contentType); } catch (err) { // 处理错误(网络错误或 4xx/5xx 响应) if (err.response) { // Spring Boot 返回的错误响应 this.error = `错误 ${err.response.status}: ${err.response.data?.message || '未知错误'}`; } else { this.error = `网络错误: ${err.message}`; } } finally { this.loading = false; } } } }; </script>
关键说明:
响应结构:
response.data
:Spring Boot 中ResponseEntity
的body
部分(通常是 JSON 对象)response.status
:HTTP 状态码(如 200、404 等)response.headers
:响应头(如content-type
)
Spring Boot 示例代码:
java
复制
下载
@RestController public class DataController { @GetMapping("/api/data") public ResponseEntity<Map<String, String>> getData() { Map<String, String> data = new HashMap<>(); data.put("message", "操作成功"); data.put("timestamp", Instant.now().toString()); // 返回 ResponseEntity(包含状态码、头信息和数据) return ResponseEntity.ok() .header("Custom-Header", "value") .body(data); } }
处理特殊场景:
二进制文件:如果返回文件流,需设置
responseType: 'blob'
js
复制
下载
axios.get('/api/file', { responseType: 'blob' }) .then(response => { const url = URL.createObjectURL(new Blob([response.data])); // 创建下载链接 });
自定义错误解析:
js
复制
下载
axios.interceptors.response.use( response => response, error => { const customError = error.response?.data?.error || "系统错误"; return Promise.reject(customError); } );
常见问题排查:
跨域问题 (CORS):
确保 Spring Boot 已配置 CORS:
java
复制
下载
@Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:5173") // Vue 开发服务器地址 .allowedMethods("*"); } }
响应数据解析失败:
检查响应头
Content-Type
是否为application/json
在 Spring Boot 中使用
@RestController
确保 JSON 序列化
认证问题:
在 axios 请求头中添加 Token:
js
复制
下载
axios.get('/api/secure', { headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` } })