热门的数据请求工具--axios

发布于:2023-02-05 ⋅ 阅读:(698) ⋅ 点赞:(0)

✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨

​💗💗你总会迎来那束光,或早,或晚 💗💗
✌✌让我们一起学习axios

✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨

axios 是目前前端最热门的请求工具, 用来向服务器发送 AJAX 请求进行数据交换.目前在面试时也经常被面试官问到的一个知识点,所以呢,在学习前有ajax,promise的前置知识的一个基础就最好啦,还没有学这两个知识的小伙伴可以看一下这两篇文章,希望对你有帮助哦~,接下来的文章是我学习axios的总结,快来一起学习吧!
ajax文章链接:https://blog.csdn.net/m0_46615524/article/details/125829369?spm=1001.2014.3001.5501
promise文章链接:https://blog.csdn.net/m0_46615524/article/details/126068415?spm=1001.2014.3001.5501

1.学习axios前的准备👈

1.安装json-server

安装这个json-server可以在30秒之内不用做任何编码就可以为我们创建一个假的,基于 REST API 的一个服务,可以让我们更好的通过axios获得数据

https://github.com/typicode/json-server

打开集成终端输入:npm install -g json-server

在这里插入图片描述

2.配置 db.json

{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}

3.开启json-server

在有db.json文件的文件夹下的终端输入:json-server --watch db.json,启动服务

在这里插入图片描述

2.axios的理解和使用👈

1.axios是什么?

  1. 前端最流行的 ajax 请求库 , Axios,是一个基于promise 的网络请求库,作用于node.js和浏览器中,它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生node.js ,http模块, 而在客户端 (浏览端) 则使用XMLHttpRequest 。
  2. react/vue 官方都推荐使用 axios 发 ajax 请求
  3. 文档: https://github.com/axios/axios

2.axios 特点

  1. 基于 xhr + promise 的异步 ajax 请求库
  2. 浏览器端/node 端都可以使用
  3. 支持请求/响应拦截器
  4. 支持请求取消
  5. 请求/响应数据转换
  6. 批量发送多个请求

3.axios常用语法

1.get请求

	 btns[0].onclick = function(){
            //发送 AJAX 请求
            axios({
                //请求类型
                method: 'GET',//获取数据
                //URL
                url: 'http://localhost:3000/posts/1',
            }).then(response => {
                console.log(response);
            });
        }

在这里插入图片描述

💬说明:获取id为1的文章

2.post请求

 //添加一篇新的文章
        btns[1].onclick = function(){
            //发送 AJAX 请求
            axios({
                //请求类型
                method: 'POST',
                //URL
                url: 'http://localhost:3000/posts',
                //设置请求体
                data: {
                    title: "今天天气不错, 还挺风和日丽的",
                    author: "张三"
                }
            }).then(response => {
                console.log(response);
            });
        }

在这里插入图片描述

💬说明:添加一篇id为2的文章,内容为请求体里的内容

3.put请求

//更新数据
        btns[2].onclick = function(){
            //发送 AJAX 请求
            axios({
                //请求类型
                method: 'PUT',
                //URL
                url: 'http://localhost:3000/posts/3',
                //设置请求体
                data: {
                    title: "今天天气不错, 还挺风和日丽的",
                    author: "李四"
                }
            }).then(response => {
                console.log(response);
            });
        }

在这里插入图片描述

💬说明:修改id为3的文章,将author改为李四

4.delete请求

 //删除数据
        btns[3].onclick = function(){
            //发送 AJAX 请求
            axios({
                //请求类型
                method: 'delete',
                //URL
                url: 'http://localhost:3000/posts/3',
            }).then(response => {
                console.log(response);
            });
        }

在这里插入图片描述

💬说明:删除id为3的文章

4.axios的其他语法

axios(config): 通用/最本质的发任意类型请求的方式
axios(url[, config]): 可以只指定 url 发 get 请求
axios.request(config): 等同于 axios(config)
axios.get(url[, config]): 发 get 请求
axios.delete(url[, config]): 发 delete 请求
axios.post(url[, data, config]): 发 post 请求

axios.put(url[, data, config]): 发 put 请求

axios.defaults.xxx: 请求的默认全局配置
axios.interceptors.request.use(): 添加请求拦截器
axios.interceptors.response.use(): 添加响应拦截器

axios.create([config]): 创建一个新的 axios(它没有下面的功能)

  1. 根据指定配置创建一个新的 axios, 也就就每个新 axios 都有自己的配置
  2. 新 axios 只是没有取消请求和批量发请求的方法, 其它所有语法都是一致的
  3. 为什么要设计这个语法?
    (1) 需求: 项目中有部分接口需要的配置与另一部分接口需要的配置不太一
    样, 如何处理
    (2) 解决: 创建 2 个新 axios, 每个都有自己特有的配置, 分别应用到不同要 求的接口请求中

axios.Cancel(): 用于创建取消请求的错误对象
axios.CancelToken(): 用于创建取消请求的 token 对象
axios.isCancel(): 是否是一个取消请求的错误
axios.all(promises): 用于批量执行多个异步请求
axios.spread(): 用来指定接收所有成功数据的回调函数的方法

在这里插入图片描述

列举

 <script>
        //获取按钮
        const btns = document.querySelectorAll('button');

        //发送 GET 请求
        btns[0].onclick = function(){
            // 相当于axios()
            axios.request({
                method:'GET',
                url: 'http://localhost:3000/comments'
            }).then(response => {
                console.log(response);
            })
        }

        //发送 POST 请求
        btns[1].onclick = function(){
            // axios()
            axios.post(
                'http://localhost:3000/comments', //url
                {                                 //请求体
                    "body": "喜大普奔",
                    "postId": 2
                }).then(response => {
                    console.log(response);
                })
        }
 </script>

结果:

在这里插入图片描述

3.axios请求响应结果的结构👈

在这里插入图片描述

1.config:响应结果的配置对象,里面包含请求头,请求类型,请求体等等数据

2.data:是响应体的结果,服务器返回的结果,是一个对象,这是axios自动将服务器返回成功进行了json解析

3.headers:响应头信息

4.request:原生的ajax请求对象,axios发生ajax请求,需要用到底层的xmlHttpRequest的实例对象,而request保存的就是当前axios发送请求时所创建的ajax请求对象,也就是xmlHttpRequest的实例对象

5.status:响应状态码

6.statusTest:响应状态字符串

4.axios的默认配置👈

​ 配置axios的默认配置可以在后续代码中减少重复性的代码的书写

   <script>
        //获取按钮
        const btns = document.querySelectorAll('button');
        //默认配置
        axios.defaults.method = 'GET';//设置默认的请求类型为 GET
        axios.defaults.baseURL = 'http://localhost:3000';//设置基础 URL
        axios.defaults.params = {id:100};
        axios.defaults.timeout = 3000;//

        btns[0].onclick = function(){
            axios({
                url: '/posts'
            }).then(response => {
                console.log(response);
            })
        }

    </script>

5.axios创建实例对象👈

    <script>
        //获取按钮
        const btns = document.querySelectorAll('button');
        
        //创建实例对象  /getJoke
        const duanzi = axios.create({
            baseURL: 'https://api.apiopen.top',
            timeout: 2000
        });

        const onather = axios.create({
            baseURL: 'https://b.com',
            timeout: 2000
        });
        //这里  duanzi 与 axios 对象的功能几近是一样的
        // duanzi({
        //     url: '/getJoke',
        // }).then(response => {
        //     console.log(response);
        // });

        duanzi.get('/getJoke').then(response => {
            console.log(response.data)
        })
    </script>

6.axios的拦截器👈

  1. 说明: 调用 axios()并不是立即发送 ajax 请求, 而是需要经历一个较长的流程
  2. 流程: 请求拦截器2 => 请求拦截器1 => 发ajax请求 => 响应拦截器1 => 响
    应拦截器 2 => 请求的回调
  3. 注意: 此流程是通过 promise 串连起来的, 请求拦截器传递的是 config, 响应
    拦截器传递的是 response
    <script>
        // Promise
        // 设置请求拦截器  config 配置对象
        axios.interceptors.request.use(function (config) {
            console.log('请求拦截器 成功 - 1号');
            //修改 config 中的参数
            config.params = {a:100};

            return config;
        }, function (error) {
            console.log('请求拦截器 失败 - 1号');
            return Promise.reject(error);
        });

        axios.interceptors.request.use(function (config) {
            console.log('请求拦截器 成功 - 2号');
            //修改 config 中的参数
            config.timeout = 2000;
            return config;
        }, function (error) {
            console.log('请求拦截器 失败 - 2号');
            return Promise.reject(error);
        });

        // 设置响应拦截器
        axios.interceptors.response.use(function (response) {
            console.log('响应拦截器 成功 1号');
            return response.data;
            // return response;
        }, function (error) {
            console.log('响应拦截器 失败 1号')
            return Promise.reject(error);
        });

        axios.interceptors.response.use(function (response) {
            console.log('响应拦截器 成功 2号')
            return response;
        }, function (error) {
            console.log('响应拦截器 失败 2号')
            return Promise.reject(error);
        });

        //发送请求
        axios({
            method: 'GET',
            url: 'http://localhost:3000/posts'
        }).then(response => {
            console.log('自定义回调处理成功的结果');
            console.log(response);
        });
    </script>   

输出:

在这里插入图片描述

7.axios取消请求👈

1.基本流程
①配置 cancelToken 对象
②缓存用于取消请求的 cancel 函数
③ 在后面特定时机调用 cancel 函数取消请求
④在错误回调中判断如果 error 是 cancel, 做相应处理

 <script>
        //获取按钮
        const btns = document.querySelectorAll('button');
        //2.声明全局变量
        let cancel = null;
        //发送请求
        btns[0].onclick = function(){
            //检测上一次的请求是否已经完成
            if(cancel !== null){
                //取消上一次的请求
                cancel();
            }
            axios({
                method: 'GET',
                url: 'http://localhost:3000/posts',
                //1. 添加配置对象的属性
                cancelToken: new axios.CancelToken(function(c){
                    //3. 将 c 的值赋值给 cancel
                    cancel = c;
                })
            }).then(response => {
                console.log(response);
                //将 cancel 的值初始化
                cancel = null;
            })
        }

        //绑定第二个事件取消请求
        btns[1].onclick = function(){
            cancel();
        }
    </script>   

对于axios的学习暂时到这里结束啦~

本文含有隐藏内容,请 开通VIP 后查看