```ts
import axios, {
AxiosInstance,
AxiosRequestConfig,
AxiosResponse,
AxiosError,
} from "axios";
import qs from "qs";
// 后端返回的数据类型
type ResponseData<T> = {
code: number;
data: T;
message: string;
};
// 创建axios实例
const axiosInstance: AxiosInstance = axios.create({
timeout: 60000,
});
// 异常拦截处理器
const errorHandler = (error: AxiosError) => {
if (error.response) {
switch (error.response.status) {
case 401:
// 登录过期错误处理
break;
case 500:
// 服务器错误处理
break;
default:
}
}
return Promise.reject(error);
};
// 请求拦截处理器
axiosInstance.interceptors.request.use((config: AxiosRequestConfig) => {
// qs是axios自带的序列化参数方式
if (
config.headers &&
config.headers["Content-Type"] &&
(config.headers["Content-Type"] as string).includes(
"application/x-www-form-urlencoded"
)
) {
config.params = qs.stringify(config.params);
}
return config;
}, errorHandler);
// 响应拦截处理器
axiosInstance.interceptors.response.use((response: AxiosResponse) => {
return response.data;
}, errorHandler);
export function request<T>(config: AxiosRequestConfig<T>): Promise<T> {
return new Promise((resolve, reject) => {
axiosInstance
.request<T, AxiosResponse<ResponseData<T>>>(config)
.then((result: AxiosResponse<ResponseData<T>>) => {
const { data } = result;
if (data.code === 0) {
resolve(data.data);
} else {
reject(data);
}
})
.catch((err: AxiosError) => {
reject(err);
});
});
}
```
博客描述
Axios的typescript封装
kitourf
Ryan rightfully isnГў t concerned about that, but it would have been ideal to name a winner entering the third preseason game to give him extended reps with the starters in what is typically the final dress rehearsal before the season opener <a href=http://buyciali.cfd>cialis 20 mg</a>
guxulty
<a href=http://finasterid.buzz>order propecia online mastercard</a> There s very little research to go on, for one thing
website
Hi there colleagues, pleasant post and nice arguments commented at this place, I am truly enjoying by these.