封装简易 AXIOS 请求库全流程

项目中需要对 axios 库进行封装,即使 axios 库已经很完美了。但是考虑到项目的耦合度以及后续是否更换请求库的需求先进行一次封装。

  • 本文按照我的想法一步步解析,如果想直接拿结果可以直接滚动到底部~
  • 另外,这篇文章的 axios 只是过渡。如需业务中使用可以 点我直达 axios 实战版

需求分析(初步封装)

首先,需要把模块拆分到一个单独的路径,方便后续引用。
考虑到 axios 的多配置性,这里是封装成一个类。方便后续一个 BaseURL 对应一个 axios 请求器。

抽离的好处多多,如果有新需求,直接改一处即可。

1
2
3
4
5
class devReq {
request(config) {
return axios.request(config);
}
}

大聪明要问了,就这?不就改个名吗?
没错,就这。还没开始呢。 上方只是简单的返回了一个 axios.request,看起来也没封装啊。 不急,咱不急。

需求二

众所周知,axios 返回的是一个 promise,且返回的一大坨并不是我们想要的数据。我们还需要通过下一级的 data 拿到。这时就可以改造下,返回我们想要的数据。

另外,也封装下 GET 请求和 POST 请求,而不是每次通过 request 传递一个 method。这里用到了解构,使后面带的参数加入到前面的 config 对象中组成新的对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class devReq {
request(config) {
return new Promise((resove, reject) => {
axios
.request(config)
.then(res => {
resove(res.data);
})
.catch(err => {
reject(err);
});
});
}

get(config) {
return this.request({ ...config, method: "get" });
}

post(config) {
return this.request({ ...config, method: "post" });
}
}

需求三

功能大体已经实现。接下来,需要实现一个 BaseURL 对应一个 axios 请求器。
使用 constructor 接受参数,且初始化 axios 新对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import axios from "axios";

class devReq {
constructor(baseURL, timeout = 10000) {
this.req = axios.create({ baseURL, timeout });
}

request(config) {
return this.req.request(config).then(res => res.data);
}

get(config) {
return this.request({ ...config, method: "get" });
}

post(config) {
return this.request({ ...config, method: "post" });
}
}

export default new devReq(); //传递baseURL

使用拦截器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import axios from "axios";

class devReq {
constructor(baseURL, timeout) {
this.req = axios.create({ baseURL, timeout });

this.req.interceptors.response.use(
res => res.data,
err => err
);
}

request(config) {
return this.req.request(config);
}

get(config) {
return this.req.request({ ...config, method: "get" });
}

post(config) {
return this.req.request({ ...config, method: "post" });
}
}

export default new devReq();