Spring Boot与Vue3 axios的交互问题

在前后端分离的项目中,前后端交互问题一直是大头。本文介绍了前端Get、Post、Put与delete四种不同请求时对应的不同代码。其中Get与Delete,Post与Put的代码其实大同小异,另外还介绍了通过axios上传文件的代码方法。

前置知识

Spring Boot与Vue3的基础知识

Get请求

前端:

    function getPerson() {
   
      axios.get("http://localhost:8081/person/22", {
   
        params: {
   
          height: 55,
          tiZhong: 174
        }
      }).then(req => {
   
        console.log(req.data);
      })
    }

后端:

    /**
     * Get Person请求
     *
     * @param weight 将接受前端传来的参数名为tiZhong的数据,因为前后端参数名不同,因此需要使用@PathParam注解
     * @param age    rest写法,将从前端接收 url中直接附带的参数名为age的数据,需要使用@PathVariabl注解从url中获取
     * @Param height 从前端接受参数名为height的数据,由于前后端参数相同,因此无需使用注解
     */
    @GetMapping("/person/{age}")
    public String getTest(@RequestParam("tiZhong") Integer weight, @PathVariable(value = "age") String age, Integer height) {
   
        System.err.println("年龄=" + age + "身高= " + height + "体重=" + weight);
        return "Hello Spring And Axios";
    }

Post请求

前端:

    function postPerson() {
   
      axios.post("http://localhost:8081/person/45",
          //body 数据
          {
   
        id: '13313',
        name: '慕随心'
      }, {
   
        params: {
   
          tiZhong: 55,
          height: 175,
        }
      }).then(req => {
   
        console.log(req.data);
      })
    }

后端:

/**
 * Post Person请求
 *
 * @param weight 将接受前端传来的参数名为tiZhong的数据,因为前后端参数名不同,因此需要使用@PathParam注解
 * @param age    rest写法,将从前端接收 url中直接附带的参数名为age的数据,需要使用@PathVariabl注解从url中获取
 * @Param height 从前端接受参数名为height的数据,由于前后端参数相同,因此无需使用注解
 * @Param person 从前端接收body中的数据,由于axios自动转换成了json格式,因此需要使用@RequestBody注解
 * Perosn类可从完整代码中找到
 */
@PostMapping("/person/{age}")
public String postTest(@RequestBody Person person, @PathVariable("age") String age, Integer height, @RequestParam("tiZhong") Integer weight) {
   
    System.err.println(person);
    System.err.println("年龄=" + age + "身高= " + height + "体重=" + weight);
    return "Hello Spring And  Axios";
}

Put请求

前端:

function putPerson() {
   
  axios.put("http://localhost:8081/person/45", {
   
    id: '13313',
    name: '慕随心'
  }, {
   
    params: {
   
      tiZhong: 55,
      height: 175
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值