在前端项目中,和后台交互获取数据这块,我们通常使用的是axios库,axios是一个基于
promise
的HTTP库,可运行在client
端和server
端。
虽然axios的使用已经很方便了,但是在实际项目中,为了接口的规则一致,来创建一个统一管理的全局方法以达到简化操作的目的。
1.安装axios
yarn add axios -D
// 或者
npm i axios -D
2.定义需要的接口
因为使用了
typescript
,所以需要先定义好一些接口,以便在后续的代码使用
export type Method = 'GET' | 'POST' | 'PUT' | 'DELETE'
export type ResponseType = 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' | 'stream'
export interface AxiosRequest {
baseURL?: string;
url: string;
data?: any;
params?: any;
method?: Method;
headers?: any;
timeout?: number;
responseType?: ResponseType;
}
export interface AxiosResponse {
data: any;
headers: any;
request?: any;
status: number;
statusText: string;
config: AxiosRequest;
}
export interface CustomResponse {
readonly status: boolean;
readonly message: string;
data: any;
origin?: any;
}
export interface GetDemo {
id: number;
str: string;
}
export interface PostDemo {
id: number;
list: Array<{
id: number;
version: number;
}>;
}
3.创建axios实例,并加入拦截器
根据指定配置创建一个实例,在这里对重复的请求做
cancel
处理,还可以对失败的请求重新发起请求操作
import axios, { AxiosRequestConfig, Method } from 'axios';
import { Loading } from 'element-ui';
import { ElLoadingComponent } from 'element-ui/types/loading';
// 定义接口
interface PendingType {
url?: string;
method?: Method;
params: any;
data: any;
cancel: Function;
}
// 取消重复请求
const pending: Array<PendingType> = [];
const CancelToken = axios.CancelToken;
// axios 实例
const instance = axios.create({
timeout: 10000,
responseType: 'json'
});
let loadingInstance: ElLoadingComponent;
// 移除重复请求
const removePending = (config: AxiosRequestConfig) => {
for (const key in pending) {
const item: number = +key;
const list: PendingType = pending[key];
// 当前请求在数组中存在时执行函数体
if (list.url === config.url && list.method === config.method && JSON.stringify(list.params) === JSON.stringify(config.params) && JSON.stringify(list.data) === JSON.stringify(config.data)) {
// 执行取消操作
list.cancel('操作太频繁,请稍后再试');
// 从数组中移除记录
pending.splice(item, 1);
}
}
};
// 添加请求拦截器
instance.interceptors.request.use(
request => {
loadingInstance = Loading.service({
text: '加载中',
background: 'rgba(0, 0, 0, 0.3)'
});
removePending(request);
request.cancelToken = new CancelToken((c) => {
pending.push({ url: request.url, method: request.method, params: request.params, data: request.data, cancel: c });
});
return request;
},
error => {
return Promise.reject(error);
}
);
// 添加响应拦截器
instance.interceptors.response.use(
response => {
loadingInstance.close();
removePending(response.config);
const errorCode = response?.data?.errorCode;
switch (errorCode) {
case '401':
// 根据errorCode,对业务做异常处理(和后端约定)
break;
default:
break;
}
return response;
},
error => {
loadingInstance.close();
const response = error.response;
// 根据返回的http状态码做不同的处理
switch (response?.status) {
case 401:
// token失效
break;
case 403:
// 没有权限
break;
case 500:
// 服务端错误
break;
case 503:
// 服务端错误
break;
default:
break;
}
// 超时重新请求
const config = error.config;
// 全局的请求次数,请求的间隙
const [RETRY_COUNT, RETRY_DELAY] = [3, 1000];
if (config && RETRY_COUNT) {
// 设置用于跟踪重试计数的变量
config.__retryCount = config.__retryCount || 0;
// 检查是否已经把重试的总数用完
if (config.__retryCount >= RETRY_COUNT) {
return Promise.reject(response || { message: error.message });
}
// 增加重试计数
config.__retryCount++;
// 创造新的Promise来处理指数后退
const backoff = new Promise((resolve) => {
setTimeout(() => {
resolve();
}, RETRY_DELAY || 1);
});
// instance重试请求的Promise
return backoff.then(() => {
return instance(config);
});
}
// eslint-disable-next-line
return Promise.reject(response || {message: error.message});
}
);
export default instance;
4.配置api字典表
制定一个url的字典表,利于后期的更新维护
/**
* API URL Dict api 字典
*/
interface UrlDict {
[key: string]: {
[key: string]: string;
};
}
const urlDict: UrlDict = {
Basic: {
GetDemo: 'admin/get',
PostDemo: 'admin/post',
}
};
const getUrl = (biz: string, UrlName: string): string => {
try {
const bizKeys = Object.keys(urlDict);
if (bizKeys.indexOf(biz) < 0) {
throw new Error('biz not in Dict');
}
let hostname = urlDict[biz][UrlName];
if (!hostname) {
throw new Error('url not in Dict');
}
if (hostname.substr(0, 1) === '/') {
hostname = hostname.substr(1);
}
return hostname;
} catch (err) {
console.error(err);
return '';
}
};
export default getUrl;
5.封装axios的基类
封装一个基类,对子类暴露
get
,post
,put
,delete
方法。便于子类的继承使用
/**
* axios基础构建
* @date 2019-12-24
*/
import Vue from 'vue';
import getUrl from './config';
import instance from './intercept';
import { AxiosRequest, CustomResponse } from './types';
class Abstract {
// 外部传入的baseUrl
protected baseURL: string = process.env.VUE_APP_BaseURL;
// 自定义header头
protected headers: object = {
ContentType: 'application/json;charset=UTF-8'
}
private apiAxios({ baseURL = this.baseURL, headers = this.headers, method, url, data, params, responseType }: AxiosRequest): Promise<CustomResponse> {
// url解析
const _url = (url as string).split('.');
url = getUrl(_url[0], _url[1]);
return new Promise((resolve, reject) => {
instance({
baseURL,
headers,
method,
url,
params,
data,
responseType
}).then((res) => {
// 200:服务端业务处理正常结束
if (res.status === 200) {
if (res.data.success) {
resolve({ status: true, message: 'success', data: res.data?.data, origin: res.data });
} else {
Vue.prototype.$message({ type: 'error', message: res.data?.errorMessage || (url + '请求失败') });
resolve({ status: false, message: res.data?.errorMessage || (url + '请求失败'), data: res.data?.data, origin: res.data });
}
} else {
resolve({ status: false, message: res.data?.errorMessage || (url + '请求失败'), data: null });
}
}).catch((err) => {
const message = err?.data?.errorMessage || err?.message || (url + '请求失败');
Vue.prototype.$message({ type: 'error', message });
// eslint-disable-next-line
reject({ status: false, message, data: null});
});
});
}
/**
* GET类型的网络请求
*/
protected getReq({ baseURL, headers, url, data, params, responseType }: AxiosRequest) {
return this.apiAxios({ baseURL, headers, method: 'GET', url, data, params, responseType });
}
/**
* POST类型的网络请求
*/
protected postReq({ baseURL, headers, url, data, params, responseType }: AxiosRequest) {
return this.apiAxios({ baseURL, headers, method: 'POST', url, data, params, responseType });
}
/**
* PUT类型的网络请求
*/
protected putReq({ baseURL, headers, url, data, params, responseType }: AxiosRequest) {
return this.apiAxios({ baseURL, headers, method: 'PUT', url, data, params, responseType });
}
/**
* DELETE类型的网络请求
*/
protected deleteReq({ baseURL, headers, url, data, params, responseType }: AxiosRequest) {
return this.apiAxios({ baseURL, headers, method: 'DELETE', url, data, params, responseType });
}
}
export default Abstract;
6.定义具体的业务请求
/**
* 基础数据 API 集合类
* 集成Abstract
* @date 2020-1-14
*/
import Abstract from '../abstract';
import { GetDemo, PostDemo } from './types';
class Basic extends Abstract {
/**
* get示例
*/
getDemo(params: GetDemo) {
return this.getReq({ url: 'Basic.GetDemo', params });
}
/**
* post示例
*/
postDemo(data: PostDemo) {
return this.postReq({ url: 'Basic.PostDemo', data });
}
}
// 单列模式返回对象
let instance;
export default (() => {
if (instance) return instance;
instance = new Basic();
return instance;
})();
以上就是我对axios的封装,有啥不完善的地方,欢迎大家指正批评
附上 github 的工程地址:vue+ts,顺手给楼主点个 star 吧