1
0

index.ts 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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 { CreateAxiosOptions, RequestOptions, Result } from './types';
  5. import { VAxios } from './Axios';
  6. import { getToken } from '/@/utils/auth';
  7. import { AxiosTransform } from './axiosTransform';
  8. import { checkStatus } from './checkStatus';
  9. import { useGlobSetting } from '/@/hooks/setting';
  10. import { useMessage } from '/@/hooks/web/useMessage';
  11. import { RequestEnum, ResultEnum, ContentTypeEnum } from '/@/enums/httpEnum';
  12. import { isString } from '/@/utils/is';
  13. import { formatRequestDate } from '/@/utils/dateUtil';
  14. import { setObjToUrlParams, deepMerge } from '/@/utils';
  15. import { errorStore } from '/@/store/modules/error';
  16. import { errorResult } from './const';
  17. import { useI18n } from '/@/hooks/web/useI18n';
  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. transformRequestData: (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 } = options;
  89. if (joinPrefix) {
  90. config.url = `${prefix}${config.url}`;
  91. }
  92. if (apiUrl && isString(apiUrl)) {
  93. config.url = `${apiUrl}${config.url}`;
  94. }
  95. if (config.method?.toUpperCase() === RequestEnum.GET) {
  96. const now = new Date().getTime();
  97. if (!isString(config.params)) {
  98. config.data = {
  99. // 给 get 请求加上时间戳参数,避免从缓存中拿数据。
  100. params: Object.assign(config.params || {}, {
  101. _t: now,
  102. }),
  103. };
  104. } else {
  105. // 兼容restful风格
  106. config.url = config.url + config.params + `?_t=${now}`;
  107. config.params = undefined;
  108. }
  109. } else {
  110. if (!isString(config.params)) {
  111. formatDate && formatRequestDate(config.params);
  112. config.data = config.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 + config.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. errorStore.setupErrorHandle(error);
  143. const { response, code, message } = error || {};
  144. const msg: string = response?.data?.error ? response.data.error.message : '';
  145. const err: string = error?.toString();
  146. try {
  147. if (code === 'ECONNABORTED' && message.indexOf('timeout') !== -1) {
  148. createMessage.error(t('sys.api.apiTimeoutMessage'));
  149. }
  150. if (err?.includes('Network Error')) {
  151. createErrorModal({
  152. title: t('sys.api.networkException'),
  153. content: t('sys.api.networkExceptionMsg'),
  154. });
  155. }
  156. } catch (error) {
  157. throw new Error(error);
  158. }
  159. checkStatus(error?.response?.status, msg);
  160. return Promise.reject(error);
  161. },
  162. };
  163. function createAxios(opt?: Partial<CreateAxiosOptions>) {
  164. return new VAxios(
  165. deepMerge(
  166. {
  167. timeout: 10 * 1000,
  168. // 基础接口地址
  169. // baseURL: globSetting.apiUrl,
  170. // 接口可能会有通用的地址部分,可以统一抽取出来
  171. prefixUrl: prefix,
  172. headers: { 'Content-Type': ContentTypeEnum.JSON },
  173. // 数据处理方式
  174. transform,
  175. // 配置项,下面的选项都可以在独立的接口请求中覆盖
  176. requestOptions: {
  177. // 默认将prefix 添加到url
  178. joinPrefix: true,
  179. // 需要对返回数据进行处理
  180. isTransformRequestResult: true,
  181. // post请求的时候添加参数到url
  182. joinParamsToUrl: false,
  183. // 格式化提交参数时间
  184. formatDate: true,
  185. // 消息提示类型
  186. errorMessageMode: 'message',
  187. // 接口地址
  188. apiUrl: globSetting.apiUrl,
  189. },
  190. },
  191. opt || {}
  192. )
  193. );
  194. }
  195. export const defHttp = createAxios();
  196. // other api url
  197. // export const otherHttp = createAxios({
  198. // requestOptions: {
  199. // apiUrl: 'xxx',
  200. // },
  201. // });