/**
* request 网络请求工具
* @Doc: https://github.com/umijs/umi-request
*/
import { clearAuthority } from '@/utils/authority';
import { getToken } from '@/services/authorityService';
import { router } from 'umi';
import { extend } from 'umi-request';
import F from '@/utils/locale';
import { notification } from 'antd';
import storage from '@/utils/storage';
import _ from 'lodash';
import JSONBig from 'json-bigint';
import { getJudgeValue } from '@/utils/common.utils';
import { getLocale } from 'umi/locale';
import { handleJsonBig } from '@/utils/untils';
export const EMPTY_DATA = { success: true, data: [], total: 0 };
const CODE_MESSAGE = {
200: '服务器成功返回请求的数据。',
201: '新建或修改数据成功。',
202: '一个请求已经进入后台排队(异步任务)。',
204: '删除数据成功。',
400: '发出的请求有错误,服务器没有进行新建或修改数据的操作。',
401: '用户没有权限(令牌、用户名、密码错误)。',
403: '用户得到授权,但是访问是被禁止的。',
404: '发出的请求针对的是不存在的记录,服务器没有进行操作。',
406: '请求的格式不可得。',
410: '请求的资源被永久删除,且不会再得到的。',
422: '当创建一个对象时,发生一个验证错误。',
500: '服务器发生错误,请检查服务器。',
502: '网关错误。',
503: '服务不可用,服务器暂时过载或维护。',
504: '网关超时。',
};
const CODE_MESSAGE_NEW = {
...CODE_MESSAGE,
400: '客户端传入参数的错误。',
401: '接口传入的 Token 非法或者已过期。',
403: '接口要访问的资源未得到授权,或服务端前置的数据不全。',
404: '接口要访问的资源不存在。',
405: '接口访问的 Method 不正确。',
500: '服务端错误。',
};
// 当错误信息是401的时候,跳转到GEELY SSO服务器登录
const backToLogin = () => {
clearAuthority();
if (storage.get('IS-HERO')) {
window.location.href = '/user/login?hero';
} else {
window.location.href = SSO_REDIRECT;
}
};
// 异常处理程序
const errorHandler = error => {
const { response = {}, data } = error || {};
const { message } = data;
const { status, url } = response;
let description = message;
const service = url.match(/\/glotaone-([a-zA-Z]*)\//)[1] || null;
if (status === 401) {
backToLogin();
return;
}
if (service) {
if (/^W.*$/.test(data.code)) {
const localeId = `common_error.${service.toLowerCase()}.${data.code}`;
const errMsg = F({ id: localeId });
notification.warning({
message: getJudgeValue(errMsg === localeId, description, errMsg),
});
return;
}
if (/^E.*$/.test(data.code)) {
const localeId = `common_error.request.${data.code}`;
const errMsg = F({ id: localeId });
notification.error({
message: getJudgeValue(errMsg === localeId, description, errMsg),
});
return;
}
}
if (!data.code) {
if (_.isString(data)) {
description = data;
notification.error({
message: `${F({ id: 'app.request.error' })}`,
description,
});
} else {
notification.error({
message: `${F({ id: 'app.request.error' })} ${status}: ${url}`,
description,
});
}
} else {
notification.error({
description,
});
}
};
// blob流处理
const handleBlob = res => {
const disposition =
res.headers.get('Content-disposition') || res.headers.get('content-disposition');
if (disposition) {
const filename =
disposition.indexOf('=') > -1
? decodeURI(disposition.substring(disposition.indexOf('=') + 1)).replace('utf-8\'\'', '')
: null;
return {
filename,
promise: res.blob(),
};
}
return res;
};
let selectedLang = getLocale();
if (selectedLang === 'zh-CN') {
selectedLang = 'cn';
} else {
selectedLang = 'en';
}
// 配置request请求时的默认参数
const request = extend({
headers: {
Accept: 'application/json',
language: selectedLang,
},
errorHandler, // 默认错误处理
credentials: 'include', // 默认请求是否带上cookie
prefix: '/mgapi',
});
// request 拦截器
request.interceptors.request.use((url, options) => {
// 新接口预处理page、size等字段
const { headers, withToken = true } = options;
if (withToken) {
headers.Authorization = getToken();
}
return {
url,
options,
headers,
};
});
// response 拦截器
request.interceptors.response.use(async res => {
try {
const { status, url } = res;
if (status === 401) {
backToLogin();
return false;
}
// token过期跳到登录页面
const json = await res.clone().json();
if (json.status === '40101' || json.code === 10114) {
notification.error({ message: json.msg });
const isHero = storage.get('IS-HERO');
clearAuthority();
window.location.href = isHero ? '/user/login?hero' : SSO_REDIRECT;
}
if (json.status === '40103') {
notification.error({ message: F({ id: 'common_error.request.40103' }) });
}
if (status !== 200) {
const message = (await res.clone().text()) || CODE_MESSAGE_NEW[status];
notification.error({
message: `${status}: ${message}`,
description: url,
});
}
// 非json类型不进行BigInt处理
if (
res.headers.get('content-type').indexOf('application/json') > -1 ||
res.headers.get('Content-Type').indexOf('application/json') > -1
) {
switch (json.code) {
case '0':
case 0:
break;
case 'E100001':
router.push('/401');
errorHandler({ response: res.clone(), data: json });
break;
case 'E100002':
backToLogin();
errorHandler({ response: res.clone(), data: json });
break;
default:
errorHandler({ response: res.clone(), data: json });
return res;
}
// 处理BigInt
const jsonBig = JSONBig.parse(await res.clone().text());
return handleJsonBig(jsonBig);
}
return res;
} catch (e) {
return handleBlob(res);
}
});
export default request;
request 网络请求工具
于 2021-11-18 16:07:53 首次发布