前言: axios是一个功能强大的网络请求库,其中拦截器又是axios的精髓。在小程序的开发或者需要手动实现ajax的时候,没有实现对请求的拦截,开发的时候非常不方便,因此手写一个简易版的axios拦截器。
拦截器的实现
1、实现思路
1、实现一个通用的请求request函数,所有请求都调用这个函数去进行网络请求
2、请求调用request函数
3、在正式发送请求前,执行请求前beforeRequest拦截函数
4、拿到beforeRequest的返回值,其返回值是修改后的请求参数config
5、正式发送请求
6、在请求响应后,执行beforeResponse函数,其返回值是对response数据处理后的值
7、request正式返回,请求结束
2、简易版axios的结构
根据实现思路得出的axios的结构
class Axios {
constructor() {
// 定义拦截器对象
this.interceptors = {}
// 默认的配置文件
this.config = {}
}
// axios的初始化函数,初始化时对config进行赋值
static create(){}
// 请求发送前的拦截函数
beforeRequest() {}
// 请求响应的拦截函数
beforeResponse() {}
// 通用的request函数
async request() {}
// 真正发送请求的函数
sendRequest(config) {}
// get请求
get(){}
// post请求
post(){}
}
export default Axios
为了实现方便,我把axios声明为一个class,里面主要实现了几个关键函数:create
、 beforeRequest
、 beforeResponse
、 request
、 sendRequest
。其中请求方法大家可以根据需求加,我这里列了两个常用的, get
、 post
。
3、具体函数的实现
1、this.interceptors
this.interceptors = {
// 请求拦截
request: {
// 给函数绑定当前的this,否则this会指向request
use: this.beforeRequest.bind(this),
success: noonFunc,
fail: noonFunc
},
// 相应拦截
response: {
use: this.beforeResponse.bind(this),
success: noonFunc,
fail: noonFunc
}
}
拦截器对象,对象里面包括了两个对象, request
、 response
,其中 use
就是调用拦截器的使用函数,如
axios.interceptors.request.use()
axios.interceptors.response.use()
2、this.config
默认的配置文件
// 默认的配置文件
this.config = {
// 请求的基础路由
baseURL: 'http://127.0.0.1/',
</