美文网首页高级JS
解析axios源码

解析axios源码

作者: 祝家庄打烊 | 来源:发表于2021-08-03 21:15 被阅读0次

大致思路是这样子的,利用promise的链式调用,对ajax进行封装,请求结果通过then方法回传给axios,下面进行了逐步分析,不对的地方还希望大家指出。


发送请求

准备Axios构造函数

构造函数主要是用来存储配置信息,default:用来存储axios传递的配置信息(如图一),interceptors:进行请求拦截(如图二),get/post/request:发送请求,这里的get/post都是依赖于request方法

function Ajax(){
    this.default = null;
    this.interceptors = {
        request: new InterceptorManger(),
        response: new InterceptorManger()
    }
}
Ajax.prototype.request = function(config){
    this.default = config;
}
Ajax.prototype.get = function(config){
    return Ajax.prototype.request(Object.assign({},{method:'get'},config));
}
Ajax.prototype.post = function(){
    return Ajax.prototype.request(Object.assign({},{method:'post'},config));
}

准备一个createInstance函数,函数的属性和方法都和Ajax实例一样

这里有人会问,为什么要准备一个createInstance函数?直接使用Ajax实例它不香吗?如果是这样的话,它就不符合AXIOS源码的设计理念了,作者是想通过AXIOS函数的方式就可以发送数据,而不是通过AXIOS实例的方式发送请求(如图三)。

function createInstance(){
    var context = new Ajax();
    var instance = Ajax.prototype.request.bind(context);
    instance.CancelToken = CancelToken;
    Object.keys(context).forEach(function(key){
        instance[key] = context[key];
    })
    Object.keys(Ajax.prototype).forEach(function(key){
        instance[key] = Ajax.prototype[key];
    })
    console.dir(instance);
    return instance;
}
var axios = createInstance();

通过request函数构建请求

请求axios是通过then的方式获取到请求的数据,所以request的返回值必须是一个promise对象,首先request函数里面需要构建一个promise.resolve对象,配置文件通过resolve传递给then,执行并返回ajax结果。这里有个注意事项:promise.then的返回结果一定是promise对象,这就是promise的链式调用

Ajax.prototype.request = function(config){
    this.default = config;
    var promise = Promise.resolve(config);
    var chinas = [dispatchRequest,undefined];
    return promise.then(chinas[0],chinas[1]);
}
function dispatchRequest(config){
    return xhrAdapter(config).then(function(response){
        return response;
    },function(error){
        console.log(error);
    })
}
// 发送ajax请求
function xhrAdapter(options){
    return new Promise(function(resolve,reject){
        options = options || {};
        options.type = (options.type || "GET").toUpperCase();
        options.dataType = options.dataType || "json";
        var params = formatParams(options.data);
        if (window.XMLHttpRequest) {
            var xhr = new XMLHttpRequest();
        } else { //IE6及其以下版本浏览器
            var xhr = new ActiveXObject('Microsoft.XMLHTTP');
        }
        if (options.type == "GET") {
            xhr.open("GET", options.url + "?" + params, true);
            xhr.send(null);
        } else if (options.type == "POST") {
            xhr.open("POST", options.url, true);
            //设置表单提交时的内容类型
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.send(params);
        }
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                var status = xhr.status;
                if (status >= 200 && status < 300) {
                    resolve({
                        config: options,
                        data: xhr.response,
                        headers: xhr.getAllResponseHeaders(),
                        request: xhr,
                        status: status,
                        statusText: xhr.statusText
                    });
                } else {
                   reject(new Error("请求失败,请求状态码:"+status));
                }
            }
        }
        if(options.cancelToken){
            options.cancelToken.promise.then(function(){
                xhr.abort();
            })
        }
    })
}
//格式化参数
function formatParams(data) {
    var arr = [];
    for (var name in data) {
        arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
    }
    arr.push(("v=" + Math.random()).replace(".",""));
    return arr.join("&");
}

准备InterceptorManger构造函数请求拦截

现在我们的主要功能都已经实现,现在主要完成一些辅助功能,这也就是axios具有特色的部分,首先需要了解请求拦截是执行在发送请求之前,响应拦截是执行在发送请求之后,在request函数内需要进行一些修改,把请求拦截成功/失败的回调函数存储在chinas数组并在发送请求之前,把响应拦截成功/失败的回调函数存储在chinas数组中并在发送请求之后,依次执行

Ajax.prototype.request = function(config){
    this.default = config;
    var promise = Promise.resolve(config);
    var chinas = [dispatchRequest,undefined];
    this.interceptors.request.handle.forEach(function(item){
        chinas.unshift(item.rejected);
        chinas.unshift(item.resolved);
    })
    this.interceptors.response.handle.forEach(function(item){
        chinas.push(item.resolved);
        chinas.push(item.rejected);
    })
    while(chinas.length>0){
        promise = promise.then(chinas.shift(),chinas.shift());
    }
    return promise;
}
function InterceptorManger(){
    this.handle = [];
}
InterceptorManger.prototype.use = function(resolved,rejected){
    this.handle.push({resolved,rejected})
}

准备CancelToken构造函数取消请求

通过axios执行cancel函数(如图四),cancel函数是CancelToken实例化promise.resolve方法,该方法执行会调用promise.then方法,在ajax中取消请求,也就相当于一个订阅发布的过程,延迟处理cancel函数

function xhrAdapter(options){
    return new Promise(function(resolve,reject){
        ......
        if(options.cancelToken){
            options.cancelToken.promise.then(function(){
                xhr.abort();
            })
        }
    })
}
function CancelToken(executor){
    var resultResolve = null;
    this.promise = new Promise(function(resolve){
        resultResolve = resolve
    })
    executor(resultResolve);
}

项目案例

相关文章

  • axios源码分析

    项目连接文档在线预览地址 axios源码分析 axios调用方法 axios 内部流程图 @ axios流程 解析...

  • Axios源码解析

    axios如何实现多种请求方式 原理: 通过数组循环来批量注册接口,统一调用同一个方法,参数差异:通过until....

  • axios源码解析

    Axios是近几年非常火的HTTP请求库,官网上介绍Axios 是一个基于 promise 的 HTTP 库,可以...

  • axios 源码解析

    实在来不及自己写了 把读过的文章先转过来 明天再进行编辑 axios项目目录结构 注:因为我们需要要看的代码都是...

  • 解析axios源码

    大致思路是这样子的,利用promise的链式调用,对ajax进行封装,请求结果通过then方法回传给axios,下...

  • Axios 源码解析

    本文不会细抠某些功能的具体实现方式,比如 config 的 merge 方式、utils 中的工具方法。而是抓住主...

  • 76.axios浏览器环境执行流程

    axios源码学习 环境搭建: github扒拉源码到本地[https://github.com/axios/ax...

  • Axios 源码解读 —— 源码实现篇

    在上两期,我们讲解了 Axios 的源码: Axios 源码解读 —— request 篇[https://git...

  • axios源码解析(二)核心

    核心函数 核心工具函数 core/*.js 1.buildFullPath.js 用于将baseURL与请求的re...

  • Axios使用及源码解析

    简介 axios 是一个用于浏览器和Node.js上的基于 Promise 的http网络库。 大纲 使用方式安装...

网友评论

    本文标题:解析axios源码

    本文链接:https://www.haomeiwen.com/subject/wmblvltx.html