index.ts 7.5 KB

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