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

Vue3解析Spring Boot ResponseEntity

在 Vue 3 中解析 Spring Boot 返回的 ResponseEntity 主要涉及处理 HTTP 响应。Spring Boot 的 ResponseEntity 通常包含状态码、响应头和响应体(JSON 数据为主)。以下是详细步骤和代码示例:


解决方案步骤:

  1. 发送 HTTP 请求:使用 axios 或 fetch 调用 Spring Boot API

  2. 处理响应:解析 JSON 响应体,获取状态码和头信息

  3. 处理异常:捕获可能的网络错误或 API 错误状态码

  4. 更新 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>

关键说明:

  1. 响应结构

    • response.data:Spring Boot 中 ResponseEntity 的 body 部分(通常是 JSON 对象)

    • response.status:HTTP 状态码(如 200、404 等)

    • response.headers:响应头(如 content-type

  2. 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);}
    }
  3. 处理特殊场景

    • 二进制文件:如果返回文件流,需设置 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);}
      );

常见问题排查:

  1. 跨域问题 (CORS)

    • 确保 Spring Boot 已配置 CORS:

      java

      复制

      下载

      @Configuration
      public class CorsConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedOrigins("http://localhost:5173") // Vue 开发服务器地址.allowedMethods("*");}
      }
  2. 响应数据解析失败

    • 检查响应头 Content-Type 是否为 application/json

    • 在 Spring Boot 中使用 @RestController 确保 JSON 序列化

  3. 认证问题

    • 在 axios 请求头中添加 Token:

      js

      复制

      下载

      axios.get('/api/secure', {headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
      })
http://www.lryc.cn/news/573886.html

相关文章:

  • select和poll用法解析
  • 如何仅用AI开发完整的小程序<4>—小程序页面创建与删除
  • 软件工程核心知识全景图:从需求到部署的系统化构建指南
  • 《算法笔记》之二(笔记)
  • DeepSeek:中国AI开源先锋的技术突破与行业革新
  • DeepSeek技术解析:开源大模型的创新突围之路
  • Unity中的Mathf.Clamp
  • 【unitrix】 4.0 类型级数值表示系统(types.rs)
  • 【已解决】 数据库INSERT操作时,Column count doesn’t match value count at row 1
  • 微处理器原理与应用篇---常见基础知识(6)
  • Redis-CPP 5大类型操作
  • 72、单元测试-常用测试注解
  • vue3 el-table 行字体颜色 根据字段改变
  • 在 Windows 和 Linux 下使用 C/C++ 连接 MySQL 的详细指南
  • SQL 中 HAVING COUNT (1)>1 与 HAVING COUNT (*)>1 的深度解析
  • Spring Boot Actuator 跟踪HTTP请求和响应
  • 开源 python 应用 开发(二)基于pyautogui、open cv 视觉识别的工具自动化
  • Python 的内置函数 help
  • python 常见数学公式函数使用详解
  • oracle rac - starwind san 磁盘共享篇
  • 【闲谈】对于c++未来的看法
  • Java面试复习:面向对象编程、JVM原理与Java 8新特性
  • Flink源码阅读环境准备全攻略:搭建高效探索的基石
  • Go语言--语法基础6--基本数据类型--数组类型(1)
  • 114. 二叉树展开为链表
  • C++插值记录
  • 开发云数据库
  • Python环境搭建竞赛
  • python的高校教师资源管理系统
  • 【Guava】0.做自己的编程语言