index.ts 7.4 KB

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