index.ts 7.2 KB

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