在前后端分离的项目中,前后端交互问题一直是大头。本文介绍了前端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