Axios请求封装
- 支持
get
、post
快捷调用 - 支持重复请求取消
- 支持通用错误处理
- 支持类型推导
import request, { AxiosError, AxiosRequestConfig, AxiosResponse, AxiosInstance, Method } from 'axios';
import { message } from 'antd';
import qs from 'qs';
export interface IResponse<T = any> {
flag: 0 | 1;
data?: T;
msg?: string;
code?: string;
}
interface IPending {
[paramsName: string]: Function;
}
let pending: IPending = {};
const removePending = (pending: IPending, config: AxiosRequestConfig): void => {
let key = `${config.url}&${config.method}`;
if (pending[key]) {
pending[key].call(config);
delete pending[key];
}
};
const axios = request.create({
withCredentials: true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
}
});
axios.interceptors.request.use(
(config: AxiosRequestConfig): AxiosRequestConfig => {
if (config.data instanceof FormData) {
config.headers['Content-Type'] = 'multipart/form-data';
} else {
config.data = qs.stringify(config.data);
}
return config;
},
(error: AxiosError): Promise<AxiosError> => Promise.reject(error)
);
axios.interceptors.response.use(
(response: AxiosResponse): AxiosResponse => response,
(error: AxiosError): Promise<AxiosError> => Promise.reject(error)
);
interface IAxiosStrongArgs {
url: string;
method?: Method;
data?: any;
handleErrorAuto?: boolean;
cancelRepeatReq?: boolean;
reqConfig?: AxiosRequestConfig;
}
const axiosStrong = async <R = any>(args: IAxiosStrongArgs): Promise<IResponse<R>> => {
const {
url,
method = 'get',
data,
handleErrorAuto = true,
cancelRepeatReq = true,
reqConfig = {}
} = args;
let config: AxiosRequestConfig = {
url,
method,
...reqConfig
};
if (cancelRepeatReq) {
removePending(pending, config);
config.cancelToken = new request.CancelToken((c: Function) => {
pending[`${config.url}&${config.method}`] = c;
});
}
try {
let { data: response }: AxiosResponse<IResponse<R>> = await axios({
url,
method,
data,
...config
});
if (response.flag === 0 && handleErrorAuto) {
message.error(response.msg);
}
return response;
} catch (err) {
return {
flag: 0
};
}
};
export const axiosGet = <R = any>(url: string, config: Partial<IAxiosStrongArgs> = {}) => {
return axiosStrong<R>({
url,
...config
});
};
export const axiosPost = <R = any>(url: string, data: any, config: Partial<IAxiosStrongArgs> = {}) => {
return axiosStrong<R>({
url,
method: 'post',
data,
...config
});
};
export default axiosStrong;