类型
Axios 是一个基于 promise 网络请求库,作用于 node.js 和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和 node.js 中)。在服务端它使用原生 node.> js http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。
我们一般会通过 axios.get 以及 axios.post 去发送数据请求,由于数据的返回结果是不可控的,所以 Typescript 没法帮我们推断出返回值的类型,我们可以通过主动传入泛型 T 来控制请求的返回值类型。
type IRes = { msg: string, status_code: number, data: any };
axios.post <
IRes >
("xxx", { id: "1" }).then((res) => {
// AxiosResponse<IRes, any>.data: IRes
console.log(res.data);
});
axios 的请求返回结果是 AxiosResponse 类型,我们传入的泛型 IRes,对应了 data 的泛型 T,所以当我们获取 res.data 时,拿到的就是 IRes 类型。
export interface AxiosResponse<T = any, D = any> {
data: T;
status: number;
statusText: string;
headers: AxiosResponseHeaders;
config: AxiosRequestConfig<D>;
equest?: any;
}
axios 中第二个重要的类型就是 AxiosRequestConfig 用于设置请求所需要的所有的配置信息,
可以看到 AxiosRequestConfig 有非常多的属性,
在日常工作中我们肯定没有办法对每一个工具的所有用法都了然于胸,我们可以通过对类型的查看,来获取到大部分显而易见的使用信息,
比如通过 onUploadProgress 获取上传进度,通过 timeout 设置超时时间等。
同时类型也可以规范我们的用法,当我们在使用一个不符合预期的 method 时,类型系统可以瞬间提示给我们,而不需要我们在运行时报错后,通过 debug 的方式去排查。
export interface AxiosRequestConfig<D = any{
url?: string;
method?: Method | string;
baseURL?: string;
transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
headers?: AxiosRequestHeaders;
params?: any;
paramsSerializer?: (params: any) => string;
data?: D;
timeout?: number;
timeoutErrorMessage?: string;
withCredentials?: boolean;
adapter?: AxiosAdapter;
auth?: AxiosBasicCredentials;
responseType?: ResponseType;
responseEncoding?: responseEncoding | string;
xsrfCookieName?: string;
xsrfHeaderName?: string;
onUploadProgress?: (progressEvent: any) => void;
onDownloadProgress?: (progressEvent: any) => void;
maxContentLength?: number;
validateStatus?: ((status: number) => boolean) | null;
maxBodyLength?: number;
maxRedirects?: number;
beforeRedirect?: (options: Record<string, any, responseDetails: {headers: Record<string, string}) => void;
socketPath?: string | null;
httpAgent?: any;
httpsAgent?: any;
proxy?: AxiosProxyConfig | false;
cancelToken?: CancelToken;
decompress?: boolean;
transitional?: TransitionalOptions;
signal?: AbortSignal;
insecureHTTPParser?: boolean;
env?: {FormData?: new (...args: any[]) => object;
};
}