index.ts 9.1 KB

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