Axios 封裝工具類,包含更完善的功能和更清晰的代碼結(jié)構(gòu),提升了可讀性、復(fù)用性和擴(kuò)展性:
關(guān)鍵點(diǎn)
-
響應(yīng)類型的細(xì)化
明確ApiResponse類型,使其更具通用性。 -
全局配置的抽離
將axios的默認(rèn)配置集中管理,方便后續(xù)維護(hù)。 -
攔截器的增強(qiáng)
添加更詳細(xì)的錯(cuò)誤處理和日志功能。 -
文件上傳的參數(shù)增強(qiáng)
支持動態(tài)添加額外的表單字段。 -
請求方法類型優(yōu)化
通過 TypeScript 類型定義提高類型安全性。 -
取消請求功能
添加取消請求的功能,便于在某些場景中手動中斷請求。
完整代碼
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import qs from "qs";
import { showToastFail } from "@/utils/my-utils";
import { getUrlParam } from "@/utils";
import { sign } from "@/utils/aes";
// 全局配置
const TIME_OUT = 30 * 1000;
const BASE_URL = process.env.VITE_API_BASE_URL || ""; // 支持環(huán)境變量配置
interface ApiResponse<T = any> {
code: number;
message?: string;
data: T;
msg?: string;
}
// 初始化 Axios 實(shí)例
const createAxiosInstance = (): AxiosInstance => {
const instance = axios.create({
baseURL: BASE_URL,
timeout: TIME_OUT,
headers: {
"Content-Type": "application/json",
},
paramsSerializer: params => qs.stringify(params, { arrayFormat: "brackets" }),
});
// 設(shè)置攔截器
setInterceptors(instance);
return instance;
};
const axiosInstance = createAxiosInstance();
// 請求攔截器
function setInterceptors(instance: AxiosInstance) {
const { type = "usdt", tgid = "123456" } = getUrlParam();
// 請求攔截
instance.interceptors.request.use((config: AxiosRequestConfig) => {
const params = config.params || {};
const data = config.data ? queryStringToObject(config.data) : {};
const headers = {
"Content-Type": "application/x-www-form-urlencoded",
};
config.headers = {
...headers,
...config.headers,
};
return config;
});
// 響應(yīng)攔截
instance.interceptors.response.use(
(response: AxiosResponse<ApiResponse>) => {
const { data } = response;
if (data.code !== 0) {
showToastFail(data?.message || data?.msg || "Request failed");
return Promise.reject(data);
}
return Promise.resolve(data);
},
(error: any) => {
const errorMsg = error.response?.data?.message || "Network error occurred";
showToastFail(errorMsg);
return Promise.reject(error);
}
);
}
// 查詢字符串轉(zhuǎn)換為對象
function queryStringToObject(queryString: string) {
const params: Record<string, any> = {};
new URLSearchParams(queryString).forEach((value, key) => {
params[key] = isNaN(Number(value)) ? value : Number(value);
});
return params;
}
// HTTP 工具類
export const http = {
get<T = any>(url: string, params?: any, headers?: any): Promise<ApiResponse<T>> {
return axiosInstance({
url,
method: "get",
params,
headers,
});
},
post<T = any>(url: string, data?: any, headers?: any): Promise<ApiResponse<T>> {
return axiosInstance({
url,
method: "post",
data: qs.stringify(data),
headers,
});
},
postJson<T = any>(url: string, data?: any): Promise<ApiResponse<T>> {
return axiosInstance({
url,
method: "post",
data,
headers: {
"Content-Type": "application/json",
},
});
},
put<T = any>(url: string, data?: any, headers?: any): Promise<ApiResponse<T>> {
return axiosInstance({
url,
method: "put",
data: qs.stringify(data),
headers,
});
},
delete<T = any>(url: string, params?: any, headers?: any): Promise<ApiResponse<T>> {
return axiosInstance({
url,
method: "delete",
params,
headers,
});
},
uploadFile<T = any>(url: string, file: File, additionalData?: Record<string, any>): Promise<ApiResponse<T>> {
const formData = new FormData();
formData.append("file", file);
if (additionalData) {
Object.keys(additionalData).forEach(key => formData.append(key, additionalData[key]));
}
return axiosInstance({
url,
method: "post",
data: formData,
headers: {
"Content-Type": "multipart/form-data",
},
});
},
cancelToken(): { token: any; cancel: () => void } {
const CancelToken = axios.CancelToken;
let cancel: () => void;
const token = new CancelToken(c => {
cancel = c;
});
return { token, cancel };
},
};
// 導(dǎo)出默認(rèn)實(shí)例
export default http;
調(diào)用示例
普通請求
http.get("/api/users", { page: 1, size: 10 }).then(res => {
console.log("User data:", res.data);
}).catch(err => {
console.error("Request error:", err);
});
文件上傳
const file = document.querySelector("input[type='file']").files[0];
http.uploadFile("/api/upload", file, { userId: 123 }).then(res => {
console.log("Upload success:", res.data);
}).catch(err => {
console.error("Upload failed:", err);
});
取消請求
const { token, cancel } = http.cancelToken();
http.get("/api/data", {}, { cancelToken: token })
.then(res => console.log(res))
.catch(err => console.error("Request canceled or failed:", err));
// 手動取消請求
cancel();