index.ts 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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, ContentTypeEnum } from '/@/enums/httpEnum';
  11. import { isString } from '/@/utils/is';
  12. import { getJwtToken } 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. import { PageEnum } from '/@/enums/pageEnum';
  18. import { router } from '/@/router';
  19. const globSetting = useGlobSetting();
  20. const urlPrefix = globSetting.urlPrefix;
  21. const { createMessage, createErrorModal } = useMessage();
  22. /**
  23. * @description: 数据处理,方便区分多种处理方式
  24. */
  25. const transform: AxiosTransform = {
  26. /**
  27. * @description: 处理请求数据。如果数据不是预期格式,可直接抛出错误
  28. */
  29. transformRequestHook: (res: AxiosResponse<Result>, options: RequestOptions) => {
  30. const { isReturnNativeResponse } = options;
  31. // 是否返回原生响应头 比如:需要获取响应头时使用该属性
  32. if (isReturnNativeResponse) {
  33. return res;
  34. }
  35. return res.data;
  36. },
  37. // 请求之前处理config
  38. beforeRequestHook: (config, options) => {
  39. const { apiUrl, apiUrl2, joinPrefix, joinParamsToUrl, formatDate, joinTime = true } = options;
  40. if (joinPrefix) {
  41. config.url = `${urlPrefix}${config.url}`;
  42. }
  43. if (apiUrl && isString(apiUrl)) {
  44. if (config.apiUrl2) {
  45. config.url = `${apiUrl2}${config.url}`;
  46. } else {
  47. config.url = `${apiUrl}${config.url}`;
  48. }
  49. }
  50. const params = config.params || {};
  51. const data = config.data || false;
  52. formatDate && data && !isString(data) && formatRequestDate(data);
  53. if (config.method?.toUpperCase() === RequestEnum.GET) {
  54. if (!isString(params)) {
  55. // 给 get 请求加上时间戳参数,避免从缓存中拿数据。
  56. config.params = Object.assign(params || {}, joinTimestamp(joinTime, false));
  57. } else {
  58. // 兼容restful风格
  59. config.url = config.url + params + `${joinTimestamp(joinTime, true)}`;
  60. config.params = undefined;
  61. }
  62. } else {
  63. if (!isString(params)) {
  64. formatDate && formatRequestDate(params);
  65. if (Reflect.has(config, 'data') && config.data && Object.keys(config.data).length > 0) {
  66. config.data = data;
  67. config.params = params;
  68. } else {
  69. // 非GET请求如果没有提供data,则将params视为data
  70. config.data = params;
  71. config.params = undefined;
  72. }
  73. if (joinParamsToUrl) {
  74. config.url = setObjToUrlParams(
  75. config.url as string,
  76. Object.assign({}, config.params, config.data)
  77. );
  78. }
  79. } else {
  80. // 兼容restful风格
  81. config.url = config.url + params;
  82. config.params = undefined;
  83. }
  84. }
  85. return config;
  86. },
  87. /**
  88. * @description: 请求拦截器处理
  89. */
  90. requestInterceptors: (config, options) => {
  91. // 请求之前处理config
  92. const token = getJwtToken();
  93. if (token && (config as Recordable)?.requestOptions?.withToken !== false &&config.url != '/agent/callProvider') {
  94. // jwt token
  95. // config.headers['X-Authorization'] = options.authenticationScheme ? `${options.authenticationScheme} ${token}` : token;
  96. config.headers['Authorization'] = options.authenticationScheme ? `${options.authenticationScheme} ${token}` : token;
  97. }
  98. return config;
  99. },
  100. /**
  101. * @description: 响应拦截器处理
  102. */
  103. responseInterceptors: (res: AxiosResponse<any>) => {
  104. return res;
  105. },
  106. /**
  107. * @description: 响应错误处理
  108. */
  109. responseInterceptorsCatch: (error: any) => {
  110. const { t } = useI18n();
  111. const errorLogStore = useErrorLogStoreWithOut();
  112. errorLogStore.addAjaxErrorInfo(error);
  113. const { response, code, message, config } = error || {};
  114. const errorMessageMode = config?.requestOptions?.errorMessageMode || 'none';
  115. const errorMsgIsObj = typeof response?.data === 'object';
  116. const msg: string = errorMsgIsObj
  117. ? response?.data?.message || response?.data?.msg
  118. : response?.data;
  119. const err: string = error?.toString?.() ?? '';
  120. let errMessage = '';
  121. try {
  122. if (response?.data?.status == '401' || response?.data?.message == '"Authentication failed"') {
  123. window.localStorage.clear();
  124. window.sessionStorage.clear();
  125. router.push(PageEnum.BASE_HOME);
  126. }
  127. if (code === 'ECONNABORTED' && message.indexOf('timeout') !== -1) {
  128. errMessage = t('sys.api.apiTimeoutMessage');
  129. }
  130. if (err?.includes('Network Error')) {
  131. errMessage = t('sys.api.networkExceptionMsg');
  132. }
  133. if (errMessage) {
  134. if (errorMessageMode === 'modal') {
  135. createErrorModal({ title: t('sys.api.errorTip'), content: errMessage });
  136. } else if (errorMessageMode === 'message') {
  137. createMessage.error(errMessage);
  138. }
  139. return Promise.reject(error);
  140. }
  141. } catch (error: any) {
  142. throw new Error(error);
  143. }
  144. checkStatus(error?.response?.status, msg, errorMessageMode);
  145. return Promise.reject(response.data);
  146. },
  147. };
  148. function createAxios(opt?: Partial<CreateAxiosOptions>) {
  149. return new VAxios(
  150. deepMerge(
  151. {
  152. // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#authentication_schemes
  153. // authentication schemes,e.g: Bearer
  154. // authenticationScheme: 'Bearer',
  155. // authenticationScheme: 'Bearer',
  156. authenticationScheme: '',
  157. timeout: 10 * 1000,
  158. // 基础接口地址
  159. // baseURL: globSetting.apiUrl,
  160. // 接口可能会有通用的地址部分,可以统一抽取出来
  161. urlPrefix: urlPrefix,
  162. // headers: { 'Content-Type': ContentTypeEnum.JSON },
  163. // 如果是form-data格式
  164. // headers: { 'Content-Type': ContentTypeEnum.FORM_URLENCODED },
  165. // 数据处理方式
  166. transform,
  167. // 配置项,下面的选项都可以在独立的接口请求中覆盖
  168. requestOptions: {
  169. // 默认将prefix 添加到url
  170. joinPrefix: true,
  171. // 是否返回原生响应头 比如:需要获取响应头时使用该属性
  172. isReturnNativeResponse: false,
  173. // 需要对返回数据进行处理
  174. isTransformResponse: true,
  175. // post请求的时候添加参数到url
  176. joinParamsToUrl: false,
  177. // 格式化提交参数时间
  178. formatDate: true,
  179. // 消息提示类型
  180. errorMessageMode: 'message',
  181. // 接口地址
  182. apiUrl: globSetting.apiUrl,
  183. apiUrl2: globSetting.apiUrl2,
  184. // 是否加入时间戳
  185. joinTime: true,
  186. // 忽略重复请求
  187. ignoreCancelToken: true,
  188. // 是否携带token
  189. withToken: true,
  190. },
  191. },
  192. opt || {}
  193. )
  194. );
  195. }
  196. export const defHttp = createAxios();
  197. // other api url
  198. export const otherHttp = createAxios({
  199. requestOptions: {
  200. apiUrl: 'xxx',
  201. },
  202. });