index.ts 7.0 KB

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