【卷起来】VUE3.0教程-07-异步请求处理(springboot后端)

news2024/9/22 23:37:32

🌲 服务端接口准备

  • pom文件,引入mybatis/mybatis-plus相关依赖
<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.3.1</version>
  </dependency>

  <dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <scope>runtime</scope>
  </dependency>
  <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter-test</artifactId>
    <version>2.3.1</version>
    <scope>test</scope>
  </dependency>

  <dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.1</version>
  </dependency>
</dependencies>

  • application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/study

spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

mybatis.mapper-locations=classpath*:mappers/*
mybatis.type-aliases-package=com.moxuan.vue_demo.entity
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

  • 启动类
package com.moxuan.vue_demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.moxuan.vue_demo.dao")
public class VueDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(VueDemoApplication.class, args);
    }

}
  • 工具类
package com.moxuan.vue_demo.util;

/**
 * 返回给客户端的状态码
 *
 * 封装状态码和消息的对应关系
 */
public enum ReturnCode {

    /*** 全局的returnCode,规定好后,任何人都不能变动这里面的内容  ***/
    SUCCESS("0000","操作成功"),
    BUSSINESS_EXCEPTION("1000","业务系统异常"),

    USER_NOT_LOGIN("8001","用户未登录"),
    ACCESS_FORBIDDEN("8002","无访问权限"),
    AUTHEN_FAILURE("8003","认证失败"),
    TOKEN_FORBIDDEN("8004","无访问口令,请登录后获取");

    /**
     * 状态码
     */
    private String code;
    /**
     * 返回的消息
     */
    private String msg;
    ReturnCode(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public String code() {
        return this.code;
    }

    public String msg(){
        return this.msg;
    }
}

package com.moxuan.vue_demo.util;

import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
public class Result {
    private String code;
    private String msg;
    private Object data;// 数据源

    /**
     * 当不需要携带data数据,只返回状态码和对应的消息时
     * @param returnCode
     * @return
     */
    public static Result sendResult(ReturnCode returnCode){
        Result result = new Result();
        result.setCode(returnCode.code());
        result.setMsg(returnCode.msg());
        return result;
    }

    /**
     * 当返回结果是,需要携带数据,调用这个方法
     * @param returnCode
     * @param data
     * @return
     */
    public static Result sendResult(ReturnCode returnCode,Object data) {
        Result result =  sendResult(returnCode);
        result.setData(data);
        return result;
    }

}
  • Dao接口
package com.moxuan.vue_demo.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.moxuan.vue_demo.entity.Hero;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface HeroMapper extends BaseMapper<Hero> {
}

  • service业务层
package com.moxuan.vue_demo.service;

import com.moxuan.vue_demo.dao.HeroMapper;
import com.moxuan.vue_demo.entity.Hero;
import com.moxuan.vue_demo.util.Result;
import com.moxuan.vue_demo.util.ReturnCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class HeroService {
    @Autowired
    private HeroMapper heroMapper;



    public Result getHeros() {
        List<Hero> heroList = heroMapper.selectList(null);
        return Result.sendResult(ReturnCode.SUCCESS,heroList);
    }

    public Result saveHero(Hero hero) {
        int count = heroMapper.insert(hero);
        if (count ==0){
            return Result.sendResult(ReturnCode.BUSSINESS_EXCEPTION);
        }
        return Result.sendResult(ReturnCode.SUCCESS);
    }

    public Result updateHeroById(Hero hero) {
        int count = heroMapper.updateById(hero);
        if (count ==0){
            return Result.sendResult(ReturnCode.BUSSINESS_EXCEPTION);
        }
        return Result.sendResult(ReturnCode.SUCCESS);
    }


    public Result deleteHero(int id) {
        int count = heroMapper.deleteById(id);
        if (count ==0){
            return Result.sendResult(ReturnCode.BUSSINESS_EXCEPTION);
        }
        return Result.sendResult(ReturnCode.SUCCESS);
    }
}
  • 控制层
package com.moxuan.vue_demo.controller;

import com.moxuan.vue_demo.service.HeroService;
import com.moxuan.vue_demo.entity.Hero;
import com.moxuan.vue_demo.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
//@RequestMapping("/api")
public class HeroController {
    @Autowired
    private HeroService service;
    @GetMapping("/hero")
    public Result getHeros(){
        log.info("查询所有的用户");
        return service.getHeros();
    }

    @PostMapping("/hero")
    public Result saveHero(Hero hero){
        return service.saveHero(hero);
    }

    @PutMapping("/hero")
    public Result updateHero(Hero hero){
        return service.updateHeroById(hero);
    }

    @DeleteMapping("/hero/{id}")
    public Result deleteHero(@PathVariable int id){
        return service.deleteHero(id);

    }
}

🌲 axios使用

🌿 axios 库下载

Axios 是一个基于promise的网络请求库,Axios的应用是需要单独安装的

npm  install --save axios

如图所示:

🌿 解决跨域问题

应用程序跨服务器访问时,经常可能出现跨域问题,这里我们先解决一下vue的跨域问题。我们找到项目的vite.config.js(vite的配置文件),添加如下代码:

server:{
  // 配置代理
  proxy:{
      // 配置代理请求前缀
      // 当vue发送localhost:5173/api/xxx请求时
      '/api': {
        // 实际上执行的是 http://localhost:8080/xxx
        target: 'http://localhost:8080/',
          changeOrigin: true,
          // 到达真实服务器地址时,去掉请求前缀/api
          // 比如前端发送请求http://localhost:5173/api/hero
          // 经过rewrite重写后会变成:http://localhost:8080/hero
          rewrite: (path) => path.replace(/^\/api/, '')
      }
  } 
}

🌿 get请求

使用axios发送get请求时,需要先在组件中导入axios

import axios from 'axios'

具体发送请求代码:

<script setup>
    import axios from 'axios'
    import {ref} from 'vue'
    const data = ref([])
    // get请求
    axios({
        method:'get',
        url:'/api/hero'  // 此处请求前需要加/api才能被代理识别
    }).then(res=>{
        console.log(res.data)
        // data.value = res.data.data;
    });
</script>

运行结果:

🌿 post请求

post请求参数需要额外处理,否则后端解析不到相关数据

  • 首先安装依赖
npm install --save querystring

  • 在组件中导入querystring
import qs from 'querystring'
  • 完整代码
<template>
    <button @click="addHero">添加数据</button>
</template>

<script setup>
    import axios from 'axios'
    import qs from 'querystring'
    import { computed } from 'vue';
   
    
    const addHero = computed(()=>{
        axios({
        method:'post',
        url:'/api/hero',
        data:qs.stringify({
            hname:"雪如意",
            sex:'女',
            job:"法师",
            level:12
        })
    }).then(res=>{
        console.log(res.data)
    });

    });
    
</script>

🌿 快捷方案

🍁 get请求
axios.get("/api/hero").then(res=>{
      console.log(res.data)
})
🍁 post请求
axios.post(
  "/api/hero",
  qs.stringify({
    hname:"马大哈",
    sex:'男',
    job:"法师",
    level:11
  })
).then(res=>{
  console.log(res.data)
})

🍁 put请求
axios.put(
  "/api/hero/",
  qs.stringify({
    id:1,
    hname:"雪如意",
    sex:'男'
  })

).then(res=>{
  console.log(res.data)
})

🍁 delete请求
axios.delete(
  "/api/hero/"+id.value

).then(res=>{
  console.log(res.data)
})

🍁 完整代码:

<template>
    
    <button @click="addHero">添加数据</button><br/>
    <button @click="getAllHeros">查询数据</button><br/>
    <input type="text" v-model="id"><button @click="updateHero">修改数据</button><br/>
    <hr/>
    <input type="text" v-model="id"><button @click="deleteHero">删除数据</button><br/>
</template>

<script setup>
    import axios from 'axios'
    import qs from 'querystring'
    import { computed,ref } from 'vue';

    const getAllHeros = computed(()=>{
        axios.get("/api/hero").then(res=>{
            console.log(res.data)
        })
    })
   
    
    const addHero = computed(()=>{
        axios.post(
            "/api/hero",
            qs.stringify({
                hname:"马大哈",
                sex:'男',
                job:"法师",
                level:11
                })
        ).then(res=>{
            console.log(res.data)
        })

    });

    const id = ref(0)
    const updateHero = computed(()=>{
        
        if(id.value==0){
            alert("请输入要修改数据的id")
        }else{
            axios.put(
                "/api/hero/",
                qs.stringify({
                    id:id.value,
                    hname:"雪如意",
                    sex:'男'
                })

            ).then(res=>{
                console.log(res.data)
            })
         }
        
    })

    const deleteHero = computed(()=>{
        axios.delete(
                "/api/hero/"+id.value
            
            ).then(res=>{
                console.log(res.data)
            })
    })
    
</script>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2127096.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Split函数

Split:可以将一个完整的字符串按照指定的分隔符划分为若干个子字符串。 String[] split(String regex) :将字符串全部拆分. String[] split(String regex, int limit) :将字符串以指定的格式&#xff0c;拆分为limit 组 代码实例&#xff1a; 切割小数点&#xff0c;或\ ,需…

每日单词记背

2024年9月12日 1.discriminate&#xff1a;歧视&#xff0c;区别&#xff0c;分辨 discriminate against 歧视&#xff1b;排斥 discriminate between 区别 辨别 dis(区别)crim(罪犯)inate ->区别为罪犯->歧视 it is illegal to discriminate against women in any way.…

【Linux修行路】信号的产生

目录 ⛳️推荐 一、信号的产生 二、产生信号的系统调用 2.1 kill——给指定的进程发送指定的信号 2.2 模拟实现指令 kill 2.3 raise——给调用的进程发送指定的信号 2.4 abort——给调用者发送 6 号信号 三、验证哪些信号不可以被捕捉 四、为什么除0和解引用空指针会给…

数据库(DB、DBMS、SQL)

今天我来讲解一下数据库和可视化数据库管理系统的使用 数据库概述 数据库 存储数据的仓库&#xff0c;数据是有组织的存储 DataBase (DB) 数据库管理系统 操纵和管理数据库的大型软件 DataBaseMangement System (DBMS) SQL 操作关系型数据库的编程语言&#xff0c;定义…

探索最佳 Shell 工具:全面测评 Bash、Zsh、Fish、Tcsh 和 Ksh

感谢浪浪云支持发布 浪浪云活动链接 &#xff1a;https://langlangy.cn/?i8afa52 文章目录 1. 简介2. 测评工具3. 测评标准4. Bash 测评4.1 易用性4.2 功能特性4.3 性能4.4 可定制性4.5 社区和支持 5. Zsh 测评5.1 易用性5.2 功能特性5.3 性能5.4 可定制性5.5 社区和支持 6. F…

C++设计模式——Builder Pattern建造者模式

一&#xff0c;建造者模式的定义 建造者模式&#xff0c;又被称为生成器模式&#xff0c;是一种创建型设计模式&#xff0c;它将复杂产品的构建过程分解为一系列简单的步骤&#xff0c;每个步骤由独立的建造者对象负责。 建造者模式常用于创建复杂的对象&#xff0c;它避免了…

网络安全架构师

网络安全架构师负责构建全面的安全框架&#xff0c;以保护组织的数字资产免受侵害&#xff0c;确保组织在数字化转型的同时维持强大的安全防护。 摩根大通的网络安全运营副总裁兼安全架构总监Lester Nichols强调&#xff0c;成为网络安全架构师对现代企业至关重要&#xff0c;…

单向链表之创建,插入,输出(上)

文章目录 &#x1f34a;自我介绍&#x1f34a;创建&#x1f34a;插入&#x1f34a;输出 你的点赞评论就是对博主最大的鼓励 当然喜欢的小伙伴可以&#xff1a;点赞关注评论收藏&#xff08;一键四连&#xff09;哦~ &#x1f34a;自我介绍 Hello,大家好&#xff0c;我是小珑也要…

VMware Fusion虚拟机Mac版 安装Ubuntu操作系统教程

Mac分享吧 文章目录 下载镜像地址&#xff1a;[www.macfxb.cn](http://www.macfxb.cn)一、CentOS安装完成&#xff0c;软件打开效果二、Mac中安装Ubuntu虚拟机1️⃣&#xff1a;下载镜像2️⃣&#xff1a;创建虚拟机3️⃣&#xff1a;虚拟机设置4️⃣&#xff1a;虚拟机安装5️…

计算机三级 - 数据库技术 - 第十四章 数据仓库与数据挖掘 笔记

第十四章 数据仓库与数据挖掘 内容提要&#xff1a; 了解数据仓库相关技术了解数据仓库的设计、建造、运行及维护了解OLAP及多维数据模型了解数据挖掘技术 决策支持系统(DSS)&#xff1a;综合利用大量数据有机组合众多模型(数学模型和数据处理模型)&#xff0c;通过人机交互&a…

uniapp 端开发 echarts 树结构图

实现效果 &#xff1a; 1. 在uniapp 中写echarts 树结构图需要使用 <script module"echarts" lang"renderjs"> 否则会无法显示echarts 图形 rebderjs 代码 引入了 /static/echarts.min.js 是在 ECharts 在线构建 定制你的echarts <te…

001 RabbitMQ入门及安装

RabbitMQ入门及安装 文章目录 RabbitMQ入门及安装1.介绍1.AMQP和JMS2.目前主流的消息队列 2.安装1.Linux安装1.1 安装erlang1.2 RabbitMQ安装 2.Docker安装 3.核心组件 1.介绍 RabbitMQ是实现了高级消息队列协议&#xff08;AMQP&#xff09;的开源消息代理软件&#xff08;亦…

嵌入式音视频开发:探索多领域的融合与创新

摘要&#xff1a; 本文深入探讨了嵌入式音视频开发领域。从嵌入式系统的基础概念入手&#xff0c;阐述了其在音视频领域的独特地位。详细介绍了嵌入式音视频开发中涉及的硬件组件&#xff0c;如处理器、编解码器、存储设备等。分析了音视频编解码技术&#xff0c;包括常见的编解…

空间数据库概述

空间数据库简介 空间数据库是 地理信息系统 在计算机物理存储介质中存储的&#xff0c;与GIS应用相关的地理空间数据的总和。一般以一系列特定结构的文件形式组织后存储在介质上。 空间数据库的特点 可以存储、处理空间数据相比普通数据库提供更多、更复杂的数据类型以及更多…

[SWPU2019]Web1 超详细教程

老规矩先看源码&#xff0c;没找到啥提示&#xff0c;后面就是登录口对抗 弱口令试了几个不行&#xff0c;就注册了个账户登录进去 可以发布广告&#xff0c;能造成xss&#xff0c;但是没啥用啊感觉 查看广告信息的时候&#xff0c;注意到url当中存在id参数&#xff0c;可能存…

Leetcode面试经典150题-134.加油站

解法都在代码里&#xff0c;不懂就留言或者私信 class Solution {public int canCompleteCircuit(int[] gas, int[] cost) {/**如果只有一个加油站&#xff0c;那它本来就在那个为止&#xff0c;0就是它的编号?但是这只是你的想象&#xff0c;题目有个变态规定&#xff0c;自…

【linux】进程控制(2)

3. 进程等待 1. 是什么 通过系统调用 wait/waitpid 对子进程的退出状态进行检测和回收的功能 2. 为什么 僵尸进程无法杀死&#xff0c;通过进程等待来杀掉它&#xff0c;进而解决内存泄漏的问题 &#xff08;一&#xff09;进程等待的方法 a. wait : 代码 wait : 等待任意一…

解锁SAP数据的潜力:SNP Glue与SAP Datasphere的协同作用

在各种文章中&#xff0c;我们研究了客户如何利用SNP Glue与基于云的数据仓库和数据湖相结合&#xff0c;以充分利用其SAP数据。SNP Glue 通过高性能集成解决方案帮助客户解锁 SAP 数据孤岛。例如&#xff0c;可以使用SNP Glue先进的增量捕获&#xff08;CDC&#xff09;近乎实…

【Linux 报错】Ubuntu 20.04.5 LTS报错:“E: Unable to locate package xx”

问题描述&#xff1a; 在使用 &#xff08;Ubuntu 20.04.5 LTS&#xff09;学习 Linux 时&#xff0c;想要安装 tree 命令&#xff0c;出现下面的报错&#xff1a; rootiZwz9asjf1ddlt6fy1ebqpZ:~# apt install tree Reading package lists... Done Building dependency tree…

蓝光3D扫描仪用于小尺寸精密注塑零件三维检测

在现代精密制造领域&#xff0c;微小型零件的加工和检测依然极具挑战。无论是微型机械零件、电子元器件&#xff0c;汽车注塑件&#xff0c;还是高端医疗器械部件&#xff0c;制造商都必须确保零件尺寸符合设计要求。传统的检测方法已无法满足日益严苛的要求&#xff0c;企业亟…