模拟实现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">
    <!-- <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.26.0/axios.min.js"></script> -->
    <title>模拟实现axios拦截器功能</title>
</head>

<body>
    <script>
        // 构造函数
        function Axios(config) {
            this.config = config;
            // 添加拦截器
            this.interceptors = {
                request: new InterceptorManager(),
                response: new InterceptorManager()
            }
        }
        // 拦截器管理器构造函数
        function InterceptorManager() {
            this.handlers = [];
        }
        // 在管理器原型上添加use方法,将拦截器放入handlers数组中
        InterceptorManager.prototype.use = function (fulfilled, rejected) {
            this.handlers.push({
                fulfilled,
                rejected
            })
        }
        // 发送请求
        Axios.prototype.request = function (config) {
            let promise = Promise.resolve(config);
            const chains = [dispatchRequest, undefined];
            // 处理拦截器、将拦截器压入chains数组中
            // 请求拦截器往前压
            this.interceptors.request.handlers.forEach(item => {
                chains.unshift(item.fulfilled, item.rejected);
            })
            // 响应拦截器往后压
            this.interceptors.response.handlers.forEach(item => {
                chains.push(item.fulfilled, item.rejected);
            });
            console.log(chains)
            // 遍历拦截器以及发送的请求
            while (chains.length > 0) {
                promise = promise.then(chains.shift(), chains.shift())
            }
            return promise;
        }

        function dispatchRequest(config) {
            // 模拟一个成功的回调
            return new Promise((resolve, reject) => {
                resolve({
                    status: 200,
                    statusText: 'ok'
                })
            })
        }
        // 创建一个axios实例
        let context = new Axios({});
        // 创建axios函数
        let axios = Axios.prototype.request.bind(context);
        // 将context的config、interceptors属性添加到axios函数对象身上
        Object.keys(context).forEach(key => {
            axios[key] = context[key]
        });
        console.dir(axios)

        // 请求拦截器
        axios.interceptors.request.use(config => {
            console.log('请求拦截器1号');
            return config;
        }, error => {
            console.log(error);
        });
        axios.interceptors.request.use(config => {
            console.log('请求拦截器2号');
            return config;
        }, error => {
            console.log(error);
        });
        // 响应拦截器
        axios.interceptors.response.use(config => {
            console.log('响应拦截器1号');
            return config;
        }, error => {
            console.log(error);
        });
        axios.interceptors.response.use(config => {
            console.log('响应拦截器2号')
            return config;
        }, error => {
            console.log(error);
        });

        axios({
            // 因为dispatchRequest是自己简约写的,所有并没有向服务器发送ajax请求,而是在dispatchRequest函数中直接就执行了成功的回调
            method: 'GET',
            url: 'http://localhost:3000/posts'
        }).then(response => {
            // 输出dispatchRequest的返回值
            console.log(response);
        }, error => {
            console.log(error)
        })
    </script>
</body>

</html>
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值