Axios HTTP 请求 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 请求


二、Axios HTTP 请求 request 方法

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

    return staff;
}
  1. 路径带参
@GetMapping("/testGetCarryData")
public Staff testGetCarryData(@RequestParam("id") 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/myTest/testGet",
    })
    .then((response) => {
        console.log("请求成功");
        if (!response.status || 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/myTest/testGetCarryData?id=1",
    })
    .then((response) => {
        console.log("请求成功");
        if (!response.status || response.status !== 200) return;
        console.log(response.data);
    })
    .catch((error) => {
        console.log("请求失败");
        console.log(error);
    });
// 或

axios
    .request({
        method: "get",
        url: "http://localhost:9999/myTest/testGetCarryData",
        params: {
            id: 1,
        },
    })
    .then((response) => {
        console.log("请求成功");
        if (!response.status || 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("/testPost")
public Staff testPost(@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/myTest/testPost",
        data: {
            id: 1,
        },
    })
    .then((response) => {
        console.log("请求成功");
        if (!response.status || 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("/testPut")
public String testPut(@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/myTest/testPut",
        data: {
            id: 1,
            age: 40,
        },
    })
    .then((response) => {
        console.log("请求成功");
        if (!response.status || response.status !== 200) return;
        console.log(response.data);
    })
    .catch((error) => {
        console.log("请求失败");
        console.log(error);
    });
  • 输出结果
请求成功
testPut OK
4、DELETE 请求
(1)Server
@DeleteMapping("/testDelete")
public String testDelete(@RequestParam("id") 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/myTest/testDelete?id=1",
    })
    .then((response) => {
        console.log("请求成功");
        if (!response.status || response.status !== 200) return;
        console.log(response.data);
    })
    .catch((error) => {
        console.log("请求失败");
        console.log(error);
    });
// 或

axios
    .request({
        method: "delete",
        url: "http://localhost:9999/myTest/testDelete",
        params: {
            id: 1,
        },
    })
    .then((response) => {
        console.log("请求成功");
        if (!response.status || response.status !== 200) return;
        console.log(response.data);
    })
    .catch((error) => {
        console.log("请求失败");
        console.log(error);
    });
  • 输出结果
请求成功
testDelete OK
  • 11
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue通常使用Axios作为Http库来发送HTTP请求。下面是一个通用的Axios封装,可以用于发送get、put、postdelete请求。 首先,我们需要在项目中安装Axios依赖。可以使用npm或yarn命令来安装: ``` npm install axios ``` 或者 ``` yarn add axios ``` 然后,我们可以在项目中创建一个utils文件夹,并在其中创建一个http.js文件。在http.js文件中,我们可以编写通用的Axios封装代码: ```javascript import axios from 'axios'; // 创建一个axios实例 const instance = axios.create({ baseURL: 'http://api.example.com' // 设置请求的默认基本URL }); // 请求拦截器,可以在请求发送之前做一些处理,比如添加请求头 instance.interceptors.request.use( config => { // 在请求发送之前添加一个Authorization请求头(如果需要) config.headers['Authorization'] = 'Bearer ' + localStorage.getItem('token'); return config; }, error => { return Promise.reject(error); } ); // 响应拦截器,可以在请求返回之后做一些处理,比如处理错误信息 instance.interceptors.response.use( response => { // 在请求成功返回之后处理响应数据 return response; }, error => { // 在请求失败返回之后处理错误信息 return Promise.reject(error.response.data); } ); // 封装get请求 export const get = (url, params) => { return instance.get(url, { params }); }; // 封装put请求 export const put = (url, data) => { return instance.put(url, data); }; // 封装post请求 export const post = (url, data) => { return instance.post(url, data); }; // 封装delete请求 export const del = url => { return instance.delete(url); }; ``` 以上是一个简单的对Axios进行封装的例子。你可以根据自己的项目需求进行相应的修改和扩展。在组件中使用get、put、postdelete方法来发送不同类型的请求。示例代码如下: ```javascript import { get, put, post, del } from '@/utils/http'; // 使用get请求 get('/api/users').then(response => { console.log(response.data); }).catch(error => { console.error(error); }); // 使用put请求 put('/api/user/1', { name: 'John', age: 30 }).then(response => { console.log(response.data); }).catch(error => { console.error(error); }); // 使用post请求 post('/api/user', { name: 'John', age: 30 }).then(response => { console.log(response.data); }).catch(error => { console.error(error); }); // 使用delete请求 del('/api/user/1').then(response => { console.log(response.data); }).catch(error => { console.error(error); }); ``` 以上就是一个通用的Axios封装,可以用于发送get、put、postdelete请求。通过这种封装,可以简化和统一项目中的HTTP请求处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值