• Axios源码仿写与二次封装


    Axios源码解析

    https://wuwhs.gitee.io/demo/keyboard-compatible/input.html

    测试用的数据

    仿写源码

    • 定义一个createInstance用来实例化Axios并在上面挂载方法和属性
    • 调用request发送请求=>调用dispatchRequest发送请求=>调用xhrAdapter发送请求(真正在网络请求在此处发送)
    • 处理拦截器
      • 将请求拦截器unshift压入chain数组中
      • 将响应拦截器push添加到chain数组中
    • 定义一个CancelToken,通过成功回调后执行xhr.about()来取消网络请求
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Titletitle>
    head>
    <body>
        <button>发送请求button>
        <br/>
        <button>取消请求button>
        <script>
            // 声明构造函数
            function Axios(config){
                this.config=config
                this.interceptors={
                    request:new InterceptorManager(),
                    response:new InterceptorManager()
                }
            }
            // 拦截器管理器构造函数
            function InterceptorManager(){
                this.handlers=[]
            }
            InterceptorManager.prototype.use=function (fulfilled, rejected){
                this.handlers.push({
                    fulfilled,
                    rejected
                })
            }
            // 函数原型上挂载方法
            Axios.prototype.request=function (config){
                // 发送请求
                // 创建一个Promise对象
                let promise=Promise.resolve(config)
                // 声明一个数组
                const chain=[dispatchRequest,undefined] // undefined作用是占位
                // 循环数组 promise.then表示成功,那么必会执行第一个函数
                // const result=promise.then(chain[0],chain[1])
                /**
                 * 处理拦截器
                 */
                // 请求拦截器
                this.interceptors.request.handlers.forEach(item=>{
                    chain.unshift(item.fulfilled,item.rejected)
                })
                // 响应拦截器
                this.interceptors.response.handlers.forEach(item=>{
                    chain.push(item.fulfilled,item.rejected)
                })
                // 遍历
                while (chain.length>0){
                    promise=promise.then(chain.shift(),chain.shift())
                }
                return promise
    
            }
            Axios.prototype.get=function (config){
                return this.request({method: 'GET',url:config.url})
            }
            Axios.prototype.post=function (config){
                return this.request({method:'POST',url:config.url})
            }
            /**
             * dispatchRequest函数
             */
            function dispatchRequest(config){
                /**
                 * 调用适配器发送请求
                 */
                return xhrAdapter(config).then(res=>{
                    // 对响应结果进行准换处理
                    return res
                },error=>{
                    throw error
                })
            }
    
            /**
             * adapter适配器
             */
            function xhrAdapter(config){
                return new Promise(((resolve, reject) => {
                    /**
                     * 发送ajax请求
                     */
                    let xhr=new XMLHttpRequest()
                    xhr.open(config.method,config.url)
                    xhr.send()
                    xhr.onreadystatechange=function (){
                        if(xhr.readyState===4){
                            if(xhr.status>=200&&xhr.status<300){
                                resolve({
                                    // 配置对象
                                    config:config,
                                    // 响应体
                                    data:xhr.response,
                                    // 响应头
                                    headers:xhr.getAllResponseHeaders(),
                                    // xhr请求对象
                                    request:xhr,
                                    // 响应状态码
                                    status:xhr.status,
                                    // 响应状态字符串
                                    statusText:xhr.statusText,
                                })
                            }else {
                                reject(new Error('请求失败,状态码为'+xhr.status))
                            }
                        }
    
                    }
                    // 取消网络请求的处理
                    if(config.cancelToken){
                        // 对cancelToken进行回调成功处理
                        config.cancelToken.promise.then(value => {
                            xhr.abort()
                            reject(new Error("请求取消"))
                        })
                    }
                }))
            }
            // cancelToken构造函数
            function CancelToken(executor){
                // 声明一个变量
                let  resolvePromise
                // 为实例对象添加属性
                this.promise=new Promise(resolve=>{
                    // 将resolve赋值给resolvePromise
                    resolvePromise=resolve
                })
                executor(function (){
                    // 执行resolvePromise函数
                    resolvePromise()
                })
    
            }
            // 声明函数
            function createInstance(config){
                const context=new Axios(config) // 目前已经可以调方法 context.get()
                const instance=Axios.prototype.request.bind(context)
                /**
                 * 将Axios原型上方法挂载到instance上
                 */
                Object.keys(Axios.prototype).forEach(key=>{
                    instance[key]=Axios.prototype[key].bind(context)
                })
                /**
                 * 为instance函数对象添加default和interceptors
                 */
                Object.keys(context).forEach(key=>{
                    instance[key]=context[key]
                })
                return instance
            }
            const axios=createInstance()
            /**
             * 测试
             */
            // 设置请求拦截器  config 配置对象
            axios.interceptors.request.use(function one(config) {
                console.log('请求拦截器 成功 - 1号');
                return config;
            }, function one(error) {
                console.log('请求拦截器 失败 - 1号');
                return Promise.reject(error);
            });
    
            axios.interceptors.request.use(function two(config) {
                console.log('请求拦截器 成功 - 2号');
                return config;
            }, function two(error) {
                console.log('请求拦截器 失败 - 2号');
                return Promise.reject(error);
            });
    
            // 设置响应拦截器
            axios.interceptors.response.use(function (response) {
                console.log('响应拦截器 成功 1号');
                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);
            });
            const btns=document.querySelectorAll('button')
            let cancel=null
            btns[0].onclick=function (){
                if(cancel!==null){
                    // 取消还未完成的请求
                    cancel()
                }
                // 创建cancelToken的值
                let cancelToken=new CancelToken(function (c){
                    cancel=c
                })
                axios({
                    method:'get',
                    url:'http://localhost:3000/posts/1',
                    cancelToken:cancelToken
                }).then(data=>{
                    console.log(data)
                    cancel=null
                })
            }
            // 取消请求
            btns[1].onclick=function (){
                cancel()
            }
            // axios({
            //     method:'get',
            //     url:'http://localhost:3000/posts/1'
            // }).then(data=>{
            //     console.log(data)
            // })
            // axios.get({url:'http://localhost:3000/posts/1'}).then(data=>{
            //     console.log(data)
            // })
        script>
    body>
    html>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228

    二次封装

    import axios from 'axios';
    import qs from 'qs';
    /**
     * 判断是什么环境
     */
    switch (process.env.NODE_ENV) {
      // 生产环境
      case 'production':
        axios.defaults.baseURL = 'http://127.0.0.1';
        break;
      // 测试环境
      case 'test':
        axios.defaults.baseURL = 'http://127.0.0.2';
        break;
      // 默认未开发环境
      default:
        axios.defaults.baseURL = 'http://localhost:3000';
    }
    /**
     * 设置超时时间
     * 设置跨域是否携带凭证
     */
    axios.defaults.timeout = 1000;
    axios.defaults.withCredentials = true;
    /**
     * 设置请求头(可以根据实际更改)
     * x-www-form-urlencoded // xxx=xxx&xxx=xxx
     */
    axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    axios.defaults.transformRequest = (data) => qs.stringify(data);
    /**
     * 设置拦截器
     */
    axios.interceptors.request.use((config) => {
      const token = localStorage.getItem('token');
      token && (config.headers.Authorization = token);
      return config;
    }, (error) => Promise.reject(error));
    /**
     * 响应拦截器
     */
    // axios.defaults.validateStatus = (status) => {
    //   // 自定义成功状态码
    //   /^(2|3)\d{2}$/.test(status);
    // };
    axios.interceptors.response.use((response) => response.data, (error) => {
      const { response } = error;
      if (response) {
        // 服务器有结果返回
        switch (response.status) {
          case '401': // 需要验证
            break;
          case '403': // 服务器拒绝执行,一般token过期
            break;
          case '404': // 找不到地址
            break;
          default:
        }
      } else {
        if (!window.navigator.onLine) {
          // 断网处理
          return Promise.reject(new Error('没网了'));
        }
        return Promise.reject(error);
      }
    });
    export default axios;
    // 使用
    // import axios from './request.js'
    // const login=()=>{
    //   return axios.post('/login',{
    //     xxx:'xxx'
    //   })
    // }
    // export default {
    //   login
    // }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
  • 相关阅读:
    Codeforces 167B 状态设置的优化
    ChatGPT原理简介
    SpringBoot接口数据加解密实战
    记录项目安装依赖时报错“Cannot read property ‘pickAlgorithm‘ of null“
    四. 优化与源码
    安培龙IPO过会:年营收5亿 同创伟业与中移创新是股东
    深入了解 Redis 集群:分片算法和架构
    第一天商城项目
    FreeRTOS 软件定时器的使用
    post发送请求
  • 原文地址:https://blog.csdn.net/weixin_64925940/article/details/125832158