🌓 拓展创建axios静态接口
# 需求分析
目前为止, aixos 都是一个蛋里,一旦修改了 aixos 的默认配置,会影响所有的请求。希望提供一个 axios.create 的静态接口允许我们创建一个 axios.create 的静态接口允许创建一个新的 axios 实例,同时允许传入新的配置和默认配置合并,并作为新的默认配置。
🌰 例子:
const instance = axios.create({ transformRequest: [(function(data) { return qs.stringify(data) }), ...(axios.defaults.transformRequest as AxiosTransformer[])], transformResponse: [...(axios.defaults.transformResponse as AxiosTransformer[]), function(data) { if (typeof data === 'object') { data.b = 2 } return data }] }) instance({ url: '/config/post', method: 'post', data: { a: 1 } })1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
instance是利用axios.create创建的axios实例。
# 静态方法拓展
在 src/type/index.ts 中修改接口类型定义:
export interface AxiosStatic extends AxiosInstance {
create(config?: AxiosRequestConfig): AxiosInstance
}
1
2
3
2
3
create函数可以接受一个AxiosRequestConfig类型的配置作为默认配置的拓展,也可以接受不传参数。
接下来实现 axios.create 静态方法。
在 src/axios.ts 中:
function createInstance(config: AxiosRequestConfig): AxiosStatic {
const context = new Axios(config)
const instance = Axios.prototype.request.bind(context)
extend(instance, context)
return instance as AxiosStatic
}
const axios = createInstance(defaults)
axios.create = function create(config) {
return createInstance(mergeConfig(defaults, config))
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
将
createInstance方法的返回值类型设置为AxiosStatic。
axios.create的内部调用了createInstance函数,并且把参数config于defaults合并,作为新的默认配置。
# 编写测试 DEMO
const instance = axios.create({
transformRequest: [
function(data) {
return qs.stringify(data)
},
...(axios.defaults.transformRequest as AxiosTransformer[])
],
transformResponse: [
...(axios.defaults.transformResponse as AxiosTransformer[]),
function(data) {
if (typeof data === 'object') {
data.b = 2
}
return data
}
]
})
instance({
url: '/config/post',
method: 'post',
data: {
a: 1
}
}).then((res) => {
console.log(res.data)
})
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
27
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
27
通过
axios.create方法创建一个新的实例instance,并传入了transformRequest和transformResponse的配置修改了默认配置,然后通过instance发送请求,效果和之前是一样的。
编辑 (opens new window)
📢 上次更新: 2022/09/02, 10:18:16
