封装网络请求
672字约2分钟
2024-11-11
项目中封装网络请求
以下列举常用的封装方式
- ajax请求
- axios请求 ...
ajax请求封装
type Methods = "GET" | "POST" | "PUT" | "DELETE";
interface AjaxOptions {
// 请求方式 默认GET请求
method: Methods;
// 请求地址
url: string;
// 请求参数
data?: any;
config?: {
/** 配置请求头 */
headers?: { [key: string]: string };
/** 请求参数存放key值 默认query */
dataName?: string;
/** 进度条 */
onProgress?: (progress: number) => void;
};
}
/**
* 发送HTTP网络请求
*/
function request<T>(options: AjaxOptions): Promise<T> {
return new Promise((resolve, reject) => {
let { method = "GET", url, data, config } = options;
const ajax = new XMLHttpRequest();
if (method === "GET") {
url += "?";
for (const key in data) {
url += `${key}=${data[key]}&`;
}
}
ajax.open(method, url);
ajax.setRequestHeader("Content-Type", "application/json");
if (config && config.headers) {
for (const key in config.headers) {
ajax.setRequestHeader(key, config.headers[key]);
}
}
// 监听请求状态
ajax.onreadystatechange = function () {
if (ajax.readyState === 4 && ajax.status === 200) {
if (ajax.responseText === "") return;
resolve(JSON.parse(ajax.response));
} else if (ajax.status === 404) {
reject();
}
};
// 监听请求进度
ajax.onprogress = function (event: ProgressEvent<EventTarget>) {
const { loaded, total } = event;
const progress = Math.floor((loaded / total) * 100);
if (config && config.onProgress) config.onProgress(progress);
};
// 监听请求错误
ajax.onerror = function (error: ProgressEvent<EventTarget>) {
console.log("request error:", error);
reject(error);
};
if (method === "GET") {
ajax.send();
} else {
ajax.send(
data &&
JSON.stringify({ [(config && config.dataName) || "query"]: data })
);
}
});
}
type AjaxReuqset = Omit<AjaxOptions, "url" | "method">;
/** 二次封装Ajax请求 */
export default class Ajax {
static get<T>(url: string, config?: AjaxReuqset): Promise<T> {
const { data } = config || {};
return request<T>({
method: "GET",
url,
data: data || {},
});
}
static post<T>(url: string, config?: AjaxReuqset): Promise<T> {
const { data } = config || {};
return request<T>({
method: "POST",
url,
data: data || {},
});
}
}
axios请求封装
import axios from "axios";
import type {
AxiosRequestConfig,
AxiosResponse,
AxiosError,
AxiosPromise,
InternalAxiosRequestConfig,
} from "axios";
const { BASE_URL } = process.env;
const server = axios.create({
baseURL: BASE_URL,
timeout: 5000,
});
// 请求拦截器
server.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
// 处理config配置,如token等
return config;
},
(error: AxiosError) => {
console.log("请求出错:", error);
}
);
// 响应拦截器
server.interceptors.response.use(
(response: AxiosResponse) => {
// 处理不同返回结果的逻辑如:信息验证码错误、token过期等
const status = response.status;
if (status === 200) {
return Promise.resolve(response.data);
} else {
return Promise.reject(response.data);
}
},
(error: AxiosError) => {
console.log("响应出错:", error);
}
);
// 后续其他问题改造封装
type Methods = "GET" | "POST" | "PUT" | "DELETE";
function http(
method: Methods = "GET",
url: string,
data?: { [key: string]: any },
config: AxiosConfig = {
headers: {
"Content-Type": "application/json",
},
}
) {
const data_flag = method === "GET" ? true : false;
const request_config: AxiosRequestConfig = {
method,
url,
params: data_flag ? data : {},
data: data_flag ? {} : data,
...config,
};
return server(request_config);
}
type AxiosConfig = Omit<
AxiosRequestConfig,
"url" | "method" | "params" | "data"
>;
/** Axios 二次封装 */
export default class AxiosRequest {
static get(
url: string,
data: { [key: string]: any } = {},
config: AxiosConfig = {}
): AxiosPromise<any> {
return http("GET", url, data, config);
}
static post(
url: string,
data: { [key: string]: any } = {},
config: AxiosConfig = {}
): AxiosPromise<any> {
return http("POST", url, data, config);
}
static put(
url: string,
data: { [key: string]: any } = {},
config: AxiosConfig = {}
): AxiosPromise<any> {
return http("PUT", url, data, config);
}
static delete(
url: string,
data: { [key: string]: any } = {},
config: AxiosConfig = {}
): AxiosPromise<any> {
return http("DELETE", url, data, config);
}
}
axios取消请求
根据以上封装做出取消请求的案例,实际情况自行甄别.
// AbortController 是全局终止控制器,其实就是一个实例签名
const controller = new AbortController();
AxiosRequest.get("/api/test", {}, {
// 此处标识取消请求签名
signal: controller.signal,
})
// 在需要的地方直接调用,即可取消本次请求
controller.abort();