index.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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 { useErrorLogStoreWithOut } from '/@/store/modules/errorLog';
  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, isReturnNativeResponse } = options;
  31. // 是否返回原生响应头 比如:需要获取响应头时使用该属性
  32. if (isReturnNativeResponse) {
  33. return res;
  34. }
  35. // 不进行任何处理,直接返回
  36. // 用于页面代码可能需要直接获取code,data,message这些信息时开启
  37. if (!isTransformRequestResult) {
  38. return res.data;
  39. }
  40. // 错误的时候返回
  41. const { data } = res;
  42. if (!data) {
  43. // return '[HTTP] Request has no return value';
  44. throw new Error(t('sys.api.apiRequestFailed'));
  45. //return errorResult;
  46. }
  47. // 这里 code,result,message为 后台统一的字段,需要在 types.ts内修改为项目自己的接口返回格式
  48. const { code, result, message } = data;
  49. // 这里逻辑可以根据项目进行修改
  50. const hasSuccess = data && Reflect.has(data, 'code') && code === ResultEnum.SUCCESS;
  51. if (hasSuccess) {
  52. return result;
  53. }
  54. // 在此处根据自己项目的实际情况对不同的code执行不同的操作
  55. // 如果不希望中断当前请求,请return数据,否则直接抛出异常即可
  56. switch (code) {
  57. case ResultEnum.TIMEOUT:
  58. const timeoutMsg = t('sys.api.timeoutMessage');
  59. createErrorModal({
  60. title: t('sys.api.operationFailed'),
  61. content: timeoutMsg,
  62. });
  63. throw new Error(timeoutMsg);
  64. default:
  65. if (message) {
  66. // errorMessageMode=‘modal’的时候会显示modal错误弹窗,而不是消息提示,用于一些比较重要的错误
  67. // errorMessageMode='none' 一般是调用时明确表示不希望自动弹出错误提示
  68. if (options.errorMessageMode === 'modal') {
  69. createErrorModal({ title: t('sys.api.errorTip'), content: message });
  70. } else if (options.errorMessageMode === 'message') {
  71. createMessage.error(message);
  72. }
  73. }
  74. }
  75. throw new Error(message || t('sys.api.apiRequestFailed'));
  76. },
  77. // 请求之前处理config
  78. beforeRequestHook: (config, options) => {
  79. const { apiUrl, joinPrefix, joinParamsToUrl, formatDate, joinTime = true } = options;
  80. if (joinPrefix) {
  81. config.url = `${prefix}${config.url}`;
  82. }
  83. if (apiUrl && isString(apiUrl)) {
  84. config.url = `${apiUrl}${config.url}`;
  85. }
  86. const params = config.params || {};
  87. if (config.method?.toUpperCase() === RequestEnum.GET) {
  88. if (!isString(params)) {
  89. // 给 get 请求加上时间戳参数,避免从缓存中拿数据。
  90. config.params = Object.assign(params || {}, createNow(joinTime, false));
  91. } else {
  92. // 兼容restful风格
  93. config.url = config.url + params + `${createNow(joinTime, true)}`;
  94. config.params = undefined;
  95. }
  96. } else {
  97. if (!isString(params)) {
  98. formatDate && formatRequestDate(params);
  99. config.data = params;
  100. config.params = undefined;
  101. if (joinParamsToUrl) {
  102. config.url = setObjToUrlParams(config.url as string, config.data);
  103. }
  104. } else {
  105. // 兼容restful风格
  106. config.url = config.url + params;
  107. config.params = undefined;
  108. }
  109. }
  110. return config;
  111. },
  112. /**
  113. * @description: 请求拦截器处理
  114. */
  115. requestInterceptors: (config) => {
  116. // 请求之前处理config
  117. const token = getToken();
  118. if (token) {
  119. // jwt token
  120. config.headers.Authorization = token;
  121. }
  122. return config;
  123. },
  124. /**
  125. * @description: 响应错误处理
  126. */
  127. responseInterceptorsCatch: (error: any) => {
  128. const { t } = useI18n();
  129. const errorLogStore = useErrorLogStoreWithOut();
  130. errorLogStore.addAjaxErrorInfo(error);
  131. const { response, code, message } = error || {};
  132. const msg: string = response?.data?.error?.message ?? '';
  133. const err: string = error?.toString?.() ?? '';
  134. try {
  135. if (code === 'ECONNABORTED' && message.indexOf('timeout') !== -1) {
  136. createMessage.error(t('sys.api.apiTimeoutMessage'));
  137. }
  138. if (err?.includes('Network Error')) {
  139. createErrorModal({
  140. title: t('sys.api.networkException'),
  141. content: t('sys.api.networkExceptionMsg'),
  142. });
  143. }
  144. } catch (error) {
  145. throw new Error(error);
  146. }
  147. checkStatus(error?.response?.status, msg);
  148. return Promise.reject(error);
  149. },
  150. };
  151. function createAxios(opt?: Partial<CreateAxiosOptions>) {
  152. return new VAxios(
  153. deepMerge(
  154. {
  155. timeout: 10 * 1000,
  156. // 基础接口地址
  157. // baseURL: globSetting.apiUrl,
  158. // 接口可能会有通用的地址部分,可以统一抽取出来
  159. prefixUrl: prefix,
  160. headers: { 'Content-Type': ContentTypeEnum.JSON },
  161. // 如果是form-data格式
  162. // headers: { 'Content-Type': ContentTypeEnum.FORM_URLENCODED },
  163. // 数据处理方式
  164. transform,
  165. // 配置项,下面的选项都可以在独立的接口请求中覆盖
  166. requestOptions: {
  167. // 默认将prefix 添加到url
  168. joinPrefix: true,
  169. // 是否返回原生响应头 比如:需要获取响应头时使用该属性
  170. isReturnNativeResponse: false,
  171. // 需要对返回数据进行处理
  172. isTransformRequestResult: true,
  173. // post请求的时候添加参数到url
  174. joinParamsToUrl: false,
  175. // 格式化提交参数时间
  176. formatDate: true,
  177. // 消息提示类型
  178. errorMessageMode: 'message',
  179. // 接口地址
  180. apiUrl: globSetting.apiUrl,
  181. // 是否加入时间戳
  182. joinTime: true,
  183. // 忽略重复请求
  184. ignoreCancelToken: true,
  185. },
  186. },
  187. opt || {}
  188. )
  189. );
  190. }
  191. export const defHttp = createAxios();
  192. // other api url
  193. // export const otherHttp = createAxios({
  194. // requestOptions: {
  195. // apiUrl: 'xxx',
  196. // },
  197. // });