<!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>
模拟实现axios拦截器功能
最新推荐文章于 2022-11-24 16:25:53 发布