在 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'}});// 解析 ResponseEntitythis.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 {@Overridepublic 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')}` } })
-