Day27 axios

简介: 一个 ajax 请求库。
axios 的创建过程模拟实现
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <script>
        //构造函数
        function Axios(config) {
            //初始化
            this.defaults = config; //为了创建 default 默认属性
            this.intercepters = {
                request: {},
                response: {}
            }
        }
        //原型添加相关的方法
        Axios.prototype.request = function (config) {
            console.log('发送 AJAX 请求 请求的类型为 ' + config.method);
        }
        Axios.prototype.get = function (config) {
            return this.request({
                method: 'GET'
            });
        }
        Axios.prototype.post = function (config) {
            return this.request({
                method: 'POST'
            });
        }

        //声明函数
        function createInstance(config) {
            //实例化一个对象
            let context = new Axios(config); // context.get()  context.post()  但是不能当做函数使用 context() X
            //创建请求函数
            let instance = Axios.prototype.request.bind(
                context); // instance 是一个函数 并且可以 instance({})  此时 instance 不能 instance.get X
            //将 Axios.prototype 对象中的方法添加到instance函数对象中,才可以instance.get....
            Object.keys(Axios.prototype).forEach(key => {
                instance[key] = Axios.prototype[key].bind(context); // this.default  this.interceptors
            });
            //为 instance 函数对象添加属性 default 与 interceptors
            Object.keys(context).forEach(key => {
                instance[key] = context[key];
            });
            return instance;
        }

        let axios = createInstance();
        //发送请求
        // axios({method:'POST'});
        axios.get({});
        axios.post({});
    </script>

</head>

<body>

</body>

</html>
目录
相关文章
|
9月前
|
XML JSON 前端开发
Axios的特点
Axios的特点
44 0
|
13天前
|
JSON JavaScript 前端开发
axios浅析(一)
 axios 是一个轻量的 HTTP客户端 基于 XMLHttpRequest 服务来执行 HTTP 请求,支持丰富的配置,支持 Promise,支持浏览器端和 Node.js 端。自Vue2.0起,尤大宣布取消对 vue-resource 的官方推荐,转而推荐 axios。现在 axios 已经成为大部分 Vue 开发者的首选。
|
3月前
|
JSON 前端开发 JavaScript
axios的详细使用
axios的详细使用
84 1
|
3月前
|
XML 存储 JSON
Axios
Axios
29 0
|
3月前
|
JSON 前端开发 API
axios使用
axios使用
|
3月前
|
存储 设计模式 JSON
快速理解 Axios
快速理解 Axios
56 0
|
3月前
|
前端开发 JavaScript
Axios有哪些常用的方法?
Axios有哪些常用的方法?
49 0
|
10月前
axios详解
axios详解
67 0
|
11月前
|
JSON JavaScript 前端开发
axios的简单的使用
axios的简单的使用
47 0
|
JSON JavaScript 前端开发
axios是什么
axios是什么
149 1