axios 封装基础请求库,简化接口请求代码。提供以下功能
1、配置不同基础请求地址
2、接口请求loading
3、附带token
4、处理token过期
5、自动过滤参数中null、undefined、''、[]参数
6、自动trim一些字符串参数
7、接口错误自动提示
8、统一post、get请求参数传递,不同像axios那样去区分params、data
import axios from 'axios';
import { ElMessage, ElLoading } from 'element-plus';
import { useRouter } from 'vue-router';
import appConfig from '../config';
const router = useRouter();
// 通过识别路由前缀分别代理到不同的服务器
axios.defaults.headers['content-type'] = 'application/json';
axios.defaults.timeout = 50000;
export default class Request {
loading // loading 实例
instance // axios 实例
constructor(cfg = {}) {
const baseUrl = cfg.baseUrl || 'apiGateway';
this.instance = axios.create({
baseURL: appConfig.gateway[baseUrl],
});
this.setInterceptors();
}
/**
* get 请求
* @param {string} url 请求地址
* @param {json} param 参数
* @param {json} config 配置,同post
* @returns promise
*/
get(url, param = {}, config) {
return this.instance.request({
method: 'post',
url,
params: param,
config,
});
}
/**
* post 请求
* @param {string} url 请求地址
* @param {json} param 参数,网关要求,空参数也要{}
* @param {json} config 配置
* {
* showLoading: true, // 是否显示loading,默认为true
* autoShowError: true // 非200的是否自动显示错误,默认为true
* autoFilterParam:true // 自动过滤掉参数中的值为null的参数,默认为true
* autoTrim: true // 默认过滤字符串参数中两边空格,默认为true,
* needToken : true // 是否需要携带token,默认为true
* }
* @returns promise
*/
post(url, param = {}, config) {
return this.instance.request({
method: 'post',
url,
data: param,
config,
});
}
// 排除无用参数目前只过滤null、undefined、''、[],只过滤一层数据
static filterParam(params) {
if (params) {
const keys = Object.keys(params);
keys.forEach((key) => {
const item = params[key];
if (item === null || item === undefined || item === '' || (item instanceof Array && item.length === 0)) {
// eslint-disable-next-line no-param-reassign
delete params[key];
}
});
}
}
// 去除字符串参数两边空格
static autoTrimParam(params) {
if (params) {
const keys = Object.keys(params);
keys.forEach((key) => {
const item = params[key];
if (typeof item === 'string') {
// eslint-disable-next-line no-param-reassign
params[key] = item.trim();
}
});
}
}
// 添加拦截器
setInterceptors() {
this.setInterceptorsRequest();
this.setInterceptorsResponse();
}
// 添加请求拦截器
setInterceptorsRequest() {
this.instance.interceptors.request.use((config) => {
const newConfig = { ...config };
// 赋配置默认值
if (!newConfig.config) {
newConfig.config = {
showLoading: true,
autoShowError: true,
autoFilterParam: true,
autoTrim: true,
needToken: true,
};
} else {
const {
showLoading = true,
autoShowError = true,
autoFilterParam = true,
autoTrim = true,
needToken = true,
} = newConfig.config;
newConfig.config = {
showLoading, autoShowError, autoFilterParam, autoTrim, needToken,
};
}
const consumerConfig = newConfig.config;
if (consumerConfig.showLoading) {
this.loading = ElLoading.service({
lock: true,
text: '加载中...',
background: 'rgba(255, 255, 255, 0)',
});
}
const token = sessionStorage.getItem('token');
if (consumerConfig.needToken && token) {
newConfig.headers['mall-platform-authorization'] = `Bearer ${token}`;
}
if (consumerConfig.autoTrim) {
Request.autoTrimParam(newConfig.data);
Request.autoTrimParam(newConfig.params);
}
if (consumerConfig.autoFilterParam) {
Request.filterParam(newConfig.data);
Request.filterParam(newConfig.params);
}
return newConfig;
}, (error) => {
if (this.loading) {
this.loading.close();
}
ElMessage.error('客户端请求异常,请稍后重试!');
return Promise.reject(error);
});
}
// 添加响应拦截器
setInterceptorsResponse() {
this.instance.interceptors.response.use((response) => {
if (response) {
const res = response.data;
if (this.loading) {
this.loading.close();
}
if (res && res.code === 401) {
router.push('/login');
return;
}
if (response.config) {
const { config } = response.config;
// 非200提示错误
if (res && res.code !== 200 && config && config.autoShowError) {
ElMessage.error(`code:${res.status}:${res.message}`);
}
}
return res;
}
}, (error) => {
if (this.loading) {
this.loading.close();
}
ElMessage.error(error.response.data);
return Promise.reject(error);
});
}
}