在上两期,我们讲解了 Axios
的源码:
今天,我们将实现一个简易的 Axios
,用于在 Node
端实现网络请求,并支持一些基础配置,比如 baseURL、url、请求方法、拦截器、取消请求…
本次实现所有的源码都放在 这里,感兴趣的可以看看。
Axios 实例
本次我们将使用 typescript + node
来实现相关代码,这样对大家理解代码也会比较清晰。
这里,先来实现一个 Axios
类吧。
type AxiosConfig = {
url: string;
method: string;
baseURL: string;
headers: {
[key: string]: string};
params: {
};
data: {
};
adapter: Function;
cancelToken?: number;
}
class Axios {
public defaults: AxiosConfig;
public createInstance!: Function;
constructor(config: AxiosConfig) {
this.defaults = config;
this.createInstance = (cfg: AxiosConfig) => {
return new Axios({
...config, ...cfg });
};
}
}
const defaultAxios = new Axios(defaultConfig);
export default defaultAxios;
在上面,我们主要是实现了 Axios
类,使用 defaults
存储默认配置,同时声明了 createInstance
方法。该方法会创建一个新的 Axios
实例,并且会继承上一个 Axios
实例的配置。
请求方法
接下来,我们将对 https://mbd.baidu.com/newspage/api/getpcvoicelist
发起一个网络请求,将响应返回的数据输出在控制台。
我们发起请求的语法如下:
import axios from './Axios';
const service = axios.createInstance({
baseURL: 'https://mbd.baidu.com'
});
(async () => {
const reply = await service.get('/newspage/api/getpcvoicelist');
console.log(reply);
})();
request 方法
我们先来给我们的 Axios
类加上一个 request
和 get
方法吧。
import {
dispatchRequest } from './request';
class Axios {
//...
public request(configOrUrl: AxiosConfig | string, config?: AxiosConfig) {
if (typeof configOrUrl === 'string') {
config!.url = configOrUrl;
} else {
config = configOrUrl;
}
const cfg = {
...this.defaults, ...config };
return dispatchRequest(cfg);
}
public get(configOrUrl: AxiosConfig | string, config?: AxiosConfig) {
return this.request(configOrUrl, {
...(config || {
} as any), method: