基于jeecg封装
判断response是否正确响应
// desc:判断后台请求是否成功
// return: 成功 true 失败 false
export function checkResp(resp) {
return resp && resp.code == '2000'
}
请求方法封装
// 查询我的绩效列表
export function getXXXList(data, params) {
return axios({
url: `${baseUrl}/getXXXList`,
method: 'post',
data,
params
});
}
业务逻辑中调用
async netGetXXX() {
this.spinning = true;
let resp,
err = {};
try {
resp = await getXXXList(
{},
{
xxx: this.xxxId
}
);
err = resp;
} catch (error) {
// console.log(error);
err = error;
}
if (checkResp(resp)) {
const data = resp.result || [];
// console.log('获取到的record列表');
// console.log(data);
this.tableData = data;
} else {
handleErrorResp(err, '');
}
this.spinning = false;
}
axios service封装
包括对blob等的一些处理。
import Vue from 'vue';
import axios from 'axios';
import store from '@/store';
import { VueAxios } from './axios';
import router from '@/router/index';
import { ACCESS_TOKEN, TENANT_ID } from '@/store/mutation-types';
/**
* 【指定 axios的 baseURL】
* 如果手工指定 baseURL: '/jeecg-boot'
* 则映射后端域名,通过 vue.config.js
* @type {*|string}
*/
let apiBaseUrl = window._CONFIG['domianURL'] || '/jeecg-boot';
// console.log('apiBaseUrl= ', apiBaseUrl);
// 创建 axios 实例
const service = axios.create({
timeout: 60000 // 请求超时时间
});
const err = error => {
//http狀態碼 將統一處理的錯誤碼返回給業務調用方 調用方根號statusList是否爲空進行判讀是否再做錯誤提示
let statusList = [];
let returnError = {};
if (error.response) {
returnError = error.response;
let { data } = error.response;
const token = Vue.ls.get(ACCESS_TOKEN);
switch (error.response.status) {
case 403:
statusList.push(403);
Vue.prototype.$Jnotification.error({ message: '系统提示', description: '拒绝访问', duration: 4 });
break;
case 500:
statusList.push(500);
let type = error.response.request.responseType;
if (type === 'blob') {
blobToJson(data);
break;
}
if (token && data.message.includes('Token失效')) {
// update-begin- --- author:scott ------ date:20190225 ---- for:Token失效采用弹框模式,不直接跳转----
if (/wxwork|dingtalk/i.test(navigator.userAgent)) {
Vue.prototype.$Jmessage.loading('登录已过期,正在重新登陆', 0);
} else {
Vue.prototype.$Jmodal.error({
title: '登录已过期',
content: '很抱歉,登录已过期,请重新登录',
okText: '重新登录',
mask: false,
onOk: () => {
store.dispatch('Logout').then(() => {
Vue.ls.remove(ACCESS_TOKEN);
try {
let path = window.document.location.pathname;
// console.log('location pathname -> ' + path);
if (path != '/' && path.indexOf('/user/login') == -1) {
window.location.reload();
}
} catch (e) {
window.location.reload();
}
});
}
});
}
// update-end- --- author:scott ------ date:20190225 ---- for:Token失效采用弹框模式,不直接跳转----
} else {
Vue.prototype.$Jnotification.error({
message: '系统提示',
description: 'Internal Server Error',
duration: 4
});
}
break;
case 404:
statusList.push(404);
Vue.prototype.$Jnotification.error({
message: '系统提示',
description: '很抱歉,资源未找到!',
duration: 4
});
break;
case 504:
statusList.push(504);
Vue.prototype.$Jnotification.error({ message: '系统提示', description: '网络超时' });
break;
case 401:
statusList.push(401);
Vue.prototype.$Jnotification.error({
message: '系统提示',
description: '很抱歉,登录已过期,请重新登录',
duration: 4
});
if (token) {
store.dispatch('Logout').then(() => {
setTimeout(() => {
window.location.reload();
}, 1500);
});
}
break;
case 400:
statusList.push(400);
Vue.prototype.$Jnotification.error({
message: '系统提示',
description: '参数非法',
duration: 4
});
break;
case 405:
statusList.push(405);
Vue.prototype.$Jnotification.error({
message: '系统提示',
description: 'Method Not Allowed',
duration: 4
});
break;
default:
Vue.prototype.$Jnotification.error({
message: '系统提示',
description: data.message,
duration: 4
});
break;
}
} else if (error.message) {
returnError = { message: error.message };
statusList.push(408);
if (error.message.includes('timeout')) {
Vue.prototype.$Jnotification.error({ message: '系统提示', description: '网络超时' });
} else {
Vue.prototype.$Jnotification.error({ message: '系统提示', description: error.message });
}
}
returnError = { ...returnError, statusList };
return Promise.reject(returnError);
};
// request interceptor
service.interceptors.request.use(
config => {
const token = Vue.ls.get(ACCESS_TOKEN);
if (token) {
config.headers['X-Access-Token'] = token; // 让每个请求携带自定义 token 请根据实际情况自行修改
}
// update-begin--author:sunjianlei---date:20200723---for 如果当前在low-app环境,并且携带了appId,就向Header里传递appId
const $route = router.currentRoute;
if ($route && $route.name && $route.name.startsWith('low-app') && $route.params.appId) {
config.headers['X-Low-App-ID'] = $route.params.appId;
}
// update-end--author:sunjianlei---date:20200723---for 如果当前在low-app环境,并且携带了appId,就向Header里传递appId
//update-begin-author:taoyan date:2020707 for:多租户
let tenantid = Vue.ls.get(TENANT_ID);
if (!tenantid) {
tenantid = 0;
}
config.headers['tenant-id'] = tenantid;
//update-end-author:taoyan date:2020707 for:多租户
if (config.method == 'get') {
if (config.url.indexOf('sys/dict/getDictItems') < 0) {
config.params = {
_t: Date.parse(new Date()) / 1000,
...config.params
};
}
}
return config;
},
error => {
return Promise.reject(error);
}
);
// response interceptor
service.interceptors.response.use(response => {
const resType = Object.prototype.toString.call(response.data);
// console.log('resType========', resType);
const isBlob = resType == '[object Blob]';
if (isBlob || resType == '[object String]') return response;
return response.data;
}, err);
const installer = {
vm: {},
install(Vue, router = {}) {
Vue.use(VueAxios, router, service);
}
};
/**
* Blob解析
* @param data
*/
function blobToJson(data) {
let fileReader = new FileReader();
let token = Vue.ls.get(ACCESS_TOKEN);
fileReader.onload = function() {
try {
let jsonData = JSON.parse(this.result); // 说明是普通对象数据,后台转换失败
// console.log('jsonData', jsonData);
if (jsonData.status === 500) {
// console.log('token----------》', token);
if (token && jsonData.message.includes('Token失效')) {
Modal.error({
title: '登录已过期',
content: '很抱歉,登录已过期,请重新登录',
okText: '重新登录',
mask: false,
onOk: () => {
store.dispatch('Logout').then(() => {
Vue.ls.remove(ACCESS_TOKEN);
window.location.reload();
});
}
});
}
}
} catch (err) {
// 解析成对象失败,说明是正常的文件流
// console.log('blob解析fileReader返回err', err);
}
};
fileReader.readAsText(data);
}
export { installer as VueAxios, service as axios };