Axios HTTP 请求 RESTful 风格 request 方法编码模板(GET、POST、PUT、DELETE)

一、Axios

1、概述
  • Axios 是一个基于 Promise 的 HTTP 客户端,用于发送 HTTP 请求和处理 HTTP 响应
2、Axios 引入
  • 可在 BootCDN 上面选择合适的 Axios 版本,官方网址:https://www.bootcdn.cn/
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.7.4/axios.js"></script>
3、request 方法
  1. HTTP 协议中最常用的四种请求方法 GET、POST、PUT、DELETE,这些方法对应着 Axios 中的同名方法 get、post、put、delete 方法

  2. Axios 中还有一个基础的、高灵活性的 request 方法,它允许执行任何类型的 HTTP 请求


二、RESTful 风格

  1. RESTful 风格基于 HTTP 协议,强调资源的表示,即一目了然,例如,普通风格的请求 /reqUser?id=【id】 在 RESTful 风格下就是 /reqUser/{【id】}

  2. RESTful 风格与普通风格的差异主要体现在理念上,而编码风格差异不大,所以我们不需要有什么心理负担


三、Axios HTTP 请求 RESTful 风格

1、GET 请求
(1)Server
  1. 路径不带参
@GetMapping("/testRestfulGet")
public Staff testRestfulGet() {
    Staff staff = new Staff(1, "jack", 10);

    return staff;
}
  1. 路径带参
@GetMapping("/testRestfulGetCarryData/{id}")
public Staff testGetRestfulCarryData(@PathVariable Integer id) {
    HashMap<Integer, Staff> staffMap = new HashMap<>();
    staffMap.put(1, new Staff(1, "jack", 10));
    staffMap.put(2, new Staff(2, "tom", 20));
    staffMap.put(3, new Staff(3, "smith", 30));

    return staffMap.get(id);
}
(2)Client
  1. 路径不带参
axios
    .request({
        method: "get",
        url: "http://localhost:9999/myRestfulTest/testRestfulGet",
    })
    .then((response) => {
        console.log("请求成功");
        if (response.status !== 200) return;
        console.log(response.data);
    })
    .catch((error) => {
        console.log("请求失败");
        console.log(error);
    });
  • 输出结果
请求成功
{id: 1, name: 'jack', age: 10}
  1. 路径带参
axios
    .request({
        method: "get",
        url: "http://localhost:9999/myRestfulTest/testRestfulGetCarryData/1",
    })
    .then((response) => {
        console.log("请求成功");
        if (response.status !== 200) return;
        console.log(response.data);
    })
    .catch((error) => {
        console.log("请求失败");
        console.log(error);
    });
  • 输出结果
请求成功
{id: 1, name: 'jack', age: 10}
2、POST 请求
(1)Server
@PostMapping("/testRestfulPost")
public Staff testRestfulPost(@RequestBody TestPostDTO testPostDTO) {
    HashMap<Integer, Staff> staffMap = new HashMap<>();
    staffMap.put(1, new Staff(1, "jack", 10));
    staffMap.put(2, new Staff(2, "tom", 20));
    staffMap.put(3, new Staff(3, "smith", 30));

    return staffMap.get(testPostDTO.getId());
}
(2)Client
axios
    .request({
        method: "post",
        url: "http://localhost:9999/myRestfulTest/testRestfulPost",
        data: {
            id: 1,
        },
    })
    .then((response) => {
        console.log("请求成功");
        if (response.status !== 200) return;
        console.log(response.data);
    })
    .catch((error) => {
        console.log("请求失败");
        console.log(error);
    });
  • 输出结果
请求成功
{id: 1, name: 'jack', age: 10}
3、PUT 请求
(1)Server
@PutMapping("/testRestfulPut")
public String testRestfulPut(@RequestBody TestPutDTO testPutDTO) {
    HashMap<Integer, Staff> staffMap = new HashMap<>();
    staffMap.put(1, new Staff(1, "jack", 10));
    staffMap.put(2, new Staff(2, "tom", 20));
    staffMap.put(3, new Staff(3, "smith", 30));

    Staff staff = staffMap.get(testPutDTO.getId());
    staff.setAge(testPutDTO.getAge());

    return "testPut OK";
}
(2)Client
axios
    .request({
        method: "put",
        url: "http://localhost:9999/myRestfulTest/testRestfulPut",
        data: {
            id: 1,
            age: 40,
        },
    })
    .then((response) => {
        console.log("请求成功");
        if (response.status !== 200) return;
        console.log(response.data);
    })
    .catch((error) => {
        console.log("请求失败");
        console.log(error);
    });
  • 输出结果
请求成功
testPut OK
4、DELETE 请求
(1)Server
@DeleteMapping("/testRestfulDelete/{id}")
public String testRestfulDelete(@PathVariable Integer id) {
    HashMap<Integer, Staff> staffMap = new HashMap<>();
    staffMap.put(1, new Staff(1, "jack", 10));
    staffMap.put(2, new Staff(2, "tom", 20));
    staffMap.put(3, new Staff(3, "smith", 30));

    staffMap.remove(id);

    return "testDelete OK";
}
(2)Client
axios
    .request({
        method: "delete",
        url: "http://localhost:9999/myRestfulTest/testRestfulDelete/1",
    })
    .then((response) => {
        console.log("请求成功");
        if (response.status !== 200) return;
        console.log(response.data);
    })
    .catch((error) => {
        console.log("请求失败");
        console.log(error);
    });
  • 输出结果
请求成功
testDelete OK
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
RESTful API 是一种基于 HTTP 协议的 API 设计风格,它使用 HTTP 请求的不同方法(比如 GET、POST、PUT、DELETE 等)来实现对资源的增删改查操作。使用 RESTful API 可以使得前端和后端的通信更加简洁和高效。 在 Vue + Spring Boot 项目中,你可以使用 Axios 库来发送 HTTP 请求,并使用 Spring Boot 的 @RestController 注解来处理请求。 以下是一个简单的例子: 1. 前端使用 Axios 发送 GET 请求获取用户列表 ```vue <template> <div> <h1>用户列表</h1> <ul> <li v-for="user in userList" :key="user.id">{{ user.name }}</li> </ul> </div> </template> <script> import axios from 'axios' export default { data() { return { userList: [] } }, mounted() { axios.get('/api/users') .then(response => { this.userList = response.data }) .catch(error => { console.log(error) }) } } </script> ``` 2. 后端使用 @RestController 注解处理请求 ```java @RestController @RequestMapping("/api/users") public class UserController { @Autowired private UserService userService; @GetMapping public List<User> getUsers() { return userService.findAll(); } @PostMapping public User createUser(@RequestBody User user) { return userService.save(user); } @PutMapping("/{id}") public User updateUser(@PathVariable Long id, @RequestBody User user) { return userService.update(id, user); } @DeleteMapping("/{id}") public void deleteUser(@PathVariable Long id) { userService.delete(id); } } ``` 上面的代码中,@GetMapping 注解用来处理 GET 请求,@PostMapping 注解用来处理 POST 请求,@PutMapping 注解用来处理 PUT 请求,@DeleteMapping 注解用来处理 DELETE 请求。 在这个例子中,我们使用 GET 请求获取用户列表,使用 POST 请求创建用户,使用 PUT 请求更新用户,使用 DELETE 请求删除用户。 当你使用 Axios 发送请求时,它会将请求发送到 /api/users 路径,这个路径会被后端的 UserController 类中对应的方法处理。 当然,这只是一个简单的例子。在实际项目中,你需要考虑更多的问题,比如请求参数的校验、异常处理、权限控制等等。但是,使用 RESTful API 可以让你的项目更加规范和易于维护。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值