axios详解

一、axios 的理解和使用

1.1 axios 是什么?

  1. 前端最流行的 ajax 请求库
  2. react/vue 官方都推荐使用 axios 发 ajax 请求
  3. 文档: https://github.com/axios/axios

1.2 axios 特点

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

1.3 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(它没有下面的功能)
axios.Cancel(): 用于创建取消请求的错误对象
axios.CancelToken(): 用于创建取消请求的 token 对象
axios.isCancel(): 是否是一个取消请求的错误
axios.all(promises): 用于批量执行多个异步请求
axios.spread(): 用来指定接收所有成功数据的回调函数的方法
在这里插入图片描述

1.4 axios基本使用

		//获取按钮
        let btns = document.getElementsByTagName('button');
        //绑定事件
        btns[0].addEventListener('click',function() {
            //发送GET AJAX请求
            axios({
                method:'GET',
                url:'http://localhost:3000/posts/1'
            }).then(response=>{
                console.log(response);
            })
        })
        //添加一篇新的文章
        btns[1].addEventListener('click',function() {
            //发送POST AJAX请求
            axios({
                method:'POST',
                url:'http://localhost:3000/posts',
                //设置请求体
                data:{
                    title:"马上快开学了!",
                    author:"蓝朽"
                }
            }).then(response=>{
                console.log(response);
            })
        })
        //更新数据
        btns[2].addEventListener('click',function() {
            //发送PUT AJAX请求
            axios({
                method:'PUT',
                url:'http://localhost:3000/posts/3',
                //设置请求体
                data:{
                    title:"马上快开学了!",
                    author:"王五"
                }
            }).then(response=>{
                console.log(response);
            })
        })
        //删除文章
        btns[3].addEventListener('click',function() {
            //发送delete AJAX请求
            axios({
                method:'DELETE',
                url:'http://localhost:3000/posts/3',
            }).then(response=>{
                console.log(response);
            })
        })

1.5 axios.request()使用

       btns[0].addEventListener('click',function(){
            axios.request({
                method:"get",
                url:"http://localhost:3000/comments"
            }).then(response=>{
                console.log(response)
            })
       })

1.6 axios默认配置

        //获取按钮
        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);
            })
        }

1.7 axios创建实例对象

  1. 根据指定配置创建一个新的 axios, 也就就每个新 axios 都有自己的配置
  2. 新 axios 只是没有取消请求和批量发请求的方法, 其它所有语法都是一致的
  3. 为什么要设计这个语法?
    (1) 需求: 项目中有部分接口需要的配置与另一部分接口需要的配置不太一
    样, 如何处理
    (2) 解决: 创建 2 个新 axios, 每个都有自己特有的配置, 分别应用到不同要
    求的接口请求中
		//获取按钮
        const btns = document.querySelectorAll('button');
        
        //创建实例对象
        let aServer = axios.create({
            baseURL:'http://localhost:3000',
            timeout: 3000
        })
        //第二个服务器的配置
        let bServer = axios.create({
            baseURL:'http://localhost:3000',
            timeout: 3000
        })
        //这里aServer和axios对象的功能几乎一样
        aServer({
            url:'/comments'
        }).then(res=>{
            console.log(res)
        })
        //发送get请求
        aServer.get('/comments').then(res=>{console.log(res.data)})

1.8 拦截器

  1. 说明: 调用 axios()并不是立即发送 ajax 请求, 而是需要经历一个较长的流程
  2. 流程: 请求拦截器2 => 请求拦截器1 => 发ajax请求 => 响应拦截器1 => 响
    应拦截器 2 => 请求的回调
  3. 注意: 此流程是通过 promise 串连起来的, 请求拦截器传递的是 config, 响应
    拦截器传递的是 response
		// 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);
        }).catch(e=>{
            console.log("自定义失败回调");
        });

1.9 取消请求

  1. 基本流程
    配置 cancelToken 对象
    缓存用于取消请求的 cancel 函数
    在后面特定时机调用 cancel 函数取消请求
    在错误回调中判断如果 error 是 cancel, 做相应处理
  2. 实现功能
    点击按钮, 取消某个正在请求中的请求
		//获取按钮
        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();
        }

二、axios 运行的整体流程

在这里插入图片描述

  1. 整体流程:
    request(config) ==> dispatchRequest(config) ==> xhrAdapter(config)
  2. request(config):
    将请求拦截器 / dispatchRequest() / 响应拦截器 通过 promise 链串连起来,
    返回 promise
  3. dispatchRequest(config):
    转换请求数据 ===> 调用 xhrAdapter()发请求 ===> 请求返回后转换响应数
    据. 返回 promise
  4. xhrAdapter(config):
    创建 XHR 对象, 根据 config 进行相应设置, 发送特定请求, 并接收响应数据,
    返回 promise

三、如何取消未完成的请求

  1. 当配置了 cancelToken 对象时, 保存 cancel 函数
    (1) 创建一个用于将来中断请求的 cancelPromise
    (2) 并定义了一个用于取消请求的 cancel 函数
    (3) 将 cancel 函数传递出来
  2. 调用 cancel()取消请求
    (1) 执行 cacel 函数, 传入错误信息 message
    (2) 内部会让 cancelPromise 变为成功, 且成功的值为一个 Cancel 对象
    (3) 在 cancelPromise 的成功回调中中断请求, 并让发请求的 proimse 失败,
    失败的 reason 为 Cancel 对象
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝朽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值