index.ts 8.0 KB

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