index.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. // axios配置 可自行根据项目进行更改,只需更改该文件即可,其他文件可以不动
  2. // The axios configuration can be changed according to the project, just change the file, other files can be left unchanged
  3. import type { AxiosResponse } from 'axios';
  4. import type { RequestOptions, Result } from './types';
  5. import type { AxiosTransform, CreateAxiosOptions } from './axiosTransform';
  6. import { VAxios } from './Axios';
  7. import { checkStatus } from './checkStatus';
  8. import { useGlobSetting } from '/@/hooks/setting';
  9. import { useMessage } from '/@/hooks/web/useMessage';
  10. import { RequestEnum, ResultEnum, ContentTypeEnum } from '/@/enums/httpEnum';
  11. import { isString } from '/@/utils/is';
  12. import { getToken } from '/@/utils/auth';
  13. import { setObjToUrlParams, deepMerge } from '/@/utils';
  14. import { errorStore } from '/@/store/modules/error';
  15. import { errorResult } from './const';
  16. import { useI18n } from '/@/hooks/web/useI18n';
  17. import { createNow, formatRequestDate } from './helper';
  18. const globSetting = useGlobSetting();
  19. const prefix = globSetting.urlPrefix;
  20. const { createMessage, createErrorModal } = useMessage();
  21. /**
  22. * @description: 数据处理,方便区分多种处理方式
  23. */
  24. const transform: AxiosTransform = {
  25. /**
  26. * @description: 处理请求数据
  27. */
  28. transformRequestHook: (res: AxiosResponse<Result>, options: RequestOptions) => {
  29. const { t } = useI18n();
  30. const { isTransformRequestResult } = options;
  31. // 不进行任何处理,直接返回
  32. // 用于页面代码可能需要直接获取code,data,message这些信息时开启
  33. if (!isTransformRequestResult) {
  34. return res.data;
  35. }
  36. // 错误的时候返回
  37. const { data } = res;
  38. if (!data) {
  39. // return '[HTTP] Request has no return value';
  40. return errorResult;
  41. }
  42. // 这里 code,result,message为 后台统一的字段,需要在 types.ts内修改为项目自己的接口返回格式
  43. const { code, result, message } = data;
  44. // 这里逻辑可以根据项目进行修改
  45. const hasSuccess = data && Reflect.has(data, 'code') && code === ResultEnum.SUCCESS;
  46. if (!hasSuccess) {
  47. if (message) {
  48. // errorMessageMode=‘modal’的时候会显示modal错误弹窗,而不是消息提示,用于一些比较重要的错误
  49. if (options.errorMessageMode === 'modal') {
  50. createErrorModal({ title: t('sys.api.errorTip'), content: message });
  51. } else if (options.errorMessageMode === 'message') {
  52. createMessage.error(message);
  53. }
  54. }
  55. Promise.reject(new Error(message));
  56. return errorResult;
  57. }
  58. // 接口请求成功,直接返回结果
  59. if (code === ResultEnum.SUCCESS) {
  60. return result;
  61. }
  62. // 接口请求错误,统一提示错误信息
  63. if (code === ResultEnum.ERROR) {
  64. if (message) {
  65. createMessage.error(data.message);
  66. Promise.reject(new Error(message));
  67. } else {
  68. const msg = t('sys.api.errorMessage');
  69. createMessage.error(msg);
  70. Promise.reject(new Error(msg));
  71. }
  72. return errorResult;
  73. }
  74. // 登录超时
  75. if (code === ResultEnum.TIMEOUT) {
  76. const timeoutMsg = t('sys.api.timeoutMessage');
  77. createErrorModal({
  78. title: t('sys.api.operationFailed'),
  79. content: timeoutMsg,
  80. });
  81. Promise.reject(new Error(timeoutMsg));
  82. return errorResult;
  83. }
  84. return errorResult;
  85. },
  86. // 请求之前处理config
  87. beforeRequestHook: (config, options) => {
  88. const { apiUrl, joinPrefix, joinParamsToUrl, formatDate, joinTime = true } = options;
  89. if (joinPrefix) {
  90. config.url = `${prefix}${config.url}`;
  91. }
  92. if (apiUrl && isString(apiUrl)) {
  93. config.url = `${apiUrl}${config.url}`;
  94. }
  95. const params = config.params || {};
  96. if (config.method?.toUpperCase() === RequestEnum.GET) {
  97. if (!isString(params)) {
  98. // 给 get 请求加上时间戳参数,避免从缓存中拿数据。
  99. config.params = Object.assign(params || {}, createNow(joinTime, false));
  100. } else {
  101. // 兼容restful风格
  102. config.url = config.url + params + `${createNow(joinTime, true)}`;
  103. config.params = undefined;
  104. }
  105. } else {
  106. if (!isString(params)) {
  107. formatDate && formatRequestDate(params);
  108. config.data = params;
  109. config.params = undefined;
  110. if (joinParamsToUrl) {
  111. config.url = setObjToUrlParams(config.url as string, config.data);
  112. }
  113. } else {
  114. // 兼容restful风格
  115. config.url = config.url + params;
  116. config.params = undefined;
  117. }
  118. }
  119. return config;
  120. },
  121. /**
  122. * @description: 请求拦截器处理
  123. */
  124. requestInterceptors: (config) => {
  125. // 请求之前处理config
  126. const token = getToken();
  127. if (token) {
  128. // jwt token
  129. config.headers.Authorization = token;
  130. }
  131. return config;
  132. },
  133. /**
  134. * @description: 响应错误处理
  135. */
  136. responseInterceptorsCatch: (error: any) => {
  137. const { t } = useI18n();
  138. errorStore.setupErrorHandle(error);
  139. const { response, code, message } = error || {};
  140. const msg: string = response?.data?.error?.message ?? '';
  141. const err: string = error?.toString?.() ?? '';
  142. try {
  143. if (code === 'ECONNABORTED' && message.indexOf('timeout') !== -1) {
  144. createMessage.error(t('sys.api.apiTimeoutMessage'));
  145. }
  146. if (err?.includes('Network Error')) {
  147. createErrorModal({
  148. title: t('sys.api.networkException'),
  149. content: t('sys.api.networkExceptionMsg'),
  150. });
  151. }
  152. } catch (error) {
  153. throw new Error(error);
  154. }
  155. checkStatus(error?.response?.status, msg);
  156. return Promise.reject(error);
  157. },
  158. };
  159. function createAxios(opt?: Partial<CreateAxiosOptions>) {
  160. return new VAxios(
  161. deepMerge(
  162. {
  163. timeout: 10 * 1000,
  164. // 基础接口地址
  165. // baseURL: globSetting.apiUrl,
  166. // 接口可能会有通用的地址部分,可以统一抽取出来
  167. prefixUrl: prefix,
  168. headers: { 'Content-Type': ContentTypeEnum.JSON },
  169. // 如果是form-data格式
  170. // headers: { 'Content-Type': ContentTypeEnum.FORM_URLENCODED },
  171. // 数据处理方式
  172. transform,
  173. // 配置项,下面的选项都可以在独立的接口请求中覆盖
  174. requestOptions: {
  175. // 默认将prefix 添加到url
  176. joinPrefix: true,
  177. // 需要对返回数据进行处理
  178. isTransformRequestResult: true,
  179. // post请求的时候添加参数到url
  180. joinParamsToUrl: false,
  181. // 格式化提交参数时间
  182. formatDate: true,
  183. // 消息提示类型
  184. errorMessageMode: 'message',
  185. // 接口地址
  186. apiUrl: globSetting.apiUrl,
  187. // 是否加入时间戳
  188. joinTime: true,
  189. // 忽略重复请求
  190. ignoreCancelToken: true,
  191. },
  192. },
  193. opt || {}
  194. )
  195. );
  196. }
  197. export const defHttp = createAxios();
  198. // other api url
  199. // export const otherHttp = createAxios({
  200. // requestOptions: {
  201. // apiUrl: 'xxx',
  202. // },
  203. // });