index.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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 { router } from '/@/router';
  9. import { useGlobSetting } from '/@/hooks/setting';
  10. import { useMessage } from '/@/hooks/web/useMessage';
  11. import { RequestEnum, ResultEnum, ContentTypeEnum, ConfigEnum } from '/@/enums/httpEnum';
  12. import { isString } from '/@/utils/is';
  13. import { getToken, getTenantId } from '/@/utils/auth';
  14. import { setObjToUrlParams, deepMerge } from '/@/utils';
  15. import signMd5Utils from '/@/utils/encryption/signMd5Utils';
  16. import { useErrorLogStoreWithOut } from '/@/store/modules/errorLog';
  17. import { useI18n } from '/@/hooks/web/useI18n';
  18. import { joinTimestamp, formatRequestDate } from './helper';
  19. import { useUserStoreWithOut } from '/@/store/modules/user';
  20. const globSetting = useGlobSetting();
  21. const urlPrefix = globSetting.urlPrefix;
  22. const { createMessage, createErrorModal } = useMessage();
  23. /**
  24. * @description: 数据处理,方便区分多种处理方式
  25. */
  26. const transform: AxiosTransform = {
  27. /**
  28. * @description: 处理请求数据。如果数据不是预期格式,可直接抛出错误
  29. */
  30. transformRequestHook: (res: AxiosResponse<Result>, options: RequestOptions) => {
  31. const { t } = useI18n();
  32. const { isTransformResponse, isReturnNativeResponse } = options;
  33. // 是否返回原生响应头 比如:需要获取响应头时使用该属性
  34. if (isReturnNativeResponse) {
  35. return res;
  36. }
  37. // 不进行任何处理,直接返回
  38. // 用于页面代码可能需要直接获取code,data,message这些信息时开启
  39. if (!isTransformResponse) {
  40. return res.data;
  41. }
  42. // 错误的时候返回
  43. const { data } = res;
  44. if (!data) {
  45. // return '[HTTP] Request has no return value';
  46. throw new Error(t('sys.api.apiRequestFailed'));
  47. }
  48. // 这里 code,result,message为 后台统一的字段,需要在 types.ts内修改为项目自己的接口返回格式
  49. const { code, result, message, success } = data;
  50. // 这里逻辑可以根据项目进行修改
  51. const hasSuccess = data && Reflect.has(data, 'code') && (code === ResultEnum.SUCCESS || code == 200);
  52. if (hasSuccess) {
  53. if (success && message && options.successMessageMode === 'success') {
  54. //信息成功提示
  55. createMessage.success(message);
  56. }
  57. return result;
  58. } else if (data) {
  59. //lxh
  60. // console.log(data, '000000000000000');
  61. createMessage.error(message);
  62. throw new Error(message)
  63. }
  64. // 在此处根据自己项目的实际情况对不同的code执行不同的操作
  65. // 如果不希望中断当前请求,请return数据,否则直接抛出异常即可
  66. let timeoutMsg = '';
  67. switch (code) {
  68. case ResultEnum.TIMEOUT:
  69. timeoutMsg = t('sys.api.timeoutMessage');
  70. const userStore = useUserStoreWithOut();
  71. userStore.setToken(undefined);
  72. userStore.logout(true);
  73. break;
  74. default:
  75. if (message) {
  76. timeoutMsg = message;
  77. }
  78. }
  79. // errorMessageMode=‘modal’的时候会显示modal错误弹窗,而不是消息提示,用于一些比较重要的错误
  80. // errorMessageMode='none' 一般是调用时明确表示不希望自动弹出错误提示
  81. if (options.errorMessageMode === 'modal') {
  82. createErrorModal({ title: t('sys.api.errorTip'), content: timeoutMsg });
  83. } else if (options.errorMessageMode === 'message') {
  84. createMessage.error(timeoutMsg);
  85. }
  86. throw new Error(timeoutMsg || t('sys.api.apiRequestFailed'));
  87. },
  88. // 请求之前处理config
  89. beforeRequestHook: (config, options) => {
  90. const { apiUrl, joinPrefix, joinParamsToUrl, formatDate, joinTime = true, urlPrefix } = options;
  91. if (joinPrefix) {
  92. config.url = `${urlPrefix}${config.url}`;
  93. }
  94. if (apiUrl && isString(apiUrl)) {
  95. config.url = `${apiUrl}${config.url}`;
  96. }
  97. const params = config.params || {};
  98. const data = config.data || false;
  99. formatDate && data && !isString(data) && formatRequestDate(data);
  100. if (config.method?.toUpperCase() === RequestEnum.GET) {
  101. if (!isString(params)) {
  102. // 给 get 请求加上时间戳参数,避免从缓存中拿数据。
  103. config.params = Object.assign(params || {}, joinTimestamp(joinTime, false));
  104. } else {
  105. // 兼容restful风格
  106. config.url = config.url + params + `${joinTimestamp(joinTime, true)}`;
  107. config.params = undefined;
  108. }
  109. } else {
  110. if (!isString(params)) {
  111. formatDate && formatRequestDate(params);
  112. if (Reflect.has(config, 'data') && config.data && Object.keys(config.data).length > 0) {
  113. config.data = data;
  114. config.params = params;
  115. } else {
  116. // 非GET请求如果没有提供data,则将params视为data
  117. config.data = params;
  118. config.params = undefined;
  119. }
  120. if (joinParamsToUrl) {
  121. config.url = setObjToUrlParams(config.url as string, Object.assign({}, config.params, config.data));
  122. }
  123. } else {
  124. // 兼容restful风格
  125. config.url = config.url + params;
  126. config.params = undefined;
  127. }
  128. }
  129. return config;
  130. },
  131. /**
  132. * @description: 请求拦截器处理
  133. */
  134. requestInterceptors: (config: Recordable, options) => {
  135. // 请求之前处理config
  136. const token = getToken();
  137. let tenantId: string | number = getTenantId();
  138. if (token && (config as Recordable)?.requestOptions?.withToken !== false) {
  139. // jwt token
  140. config.headers.Authorization = options.authenticationScheme ? `${options.authenticationScheme} ${token}` : token;
  141. config.headers[ConfigEnum.TOKEN] = token;
  142. //--update-begin--author:liusq---date:20210831---for:将签名和时间戳,添加在请求接口 Header
  143. // update-begin--author:taoyan---date:20220421--for: VUEN-410【签名改造】 X-TIMESTAMP牵扯
  144. config.headers[ConfigEnum.TIMESTAMP] = signMd5Utils.getTimestamp();
  145. // update-end--author:taoyan---date:20220421--for: VUEN-410【签名改造】 X-TIMESTAMP牵扯
  146. config.headers[ConfigEnum.Sign] = signMd5Utils.getSign(config.url, config.params);
  147. //--update-end--author:liusq---date:20210831---for:将签名和时间戳,添加在请求接口 Header
  148. //--update-begin--author:liusq---date:20211105---for: for:将多租户id,添加在请求接口 Header
  149. if (!tenantId) {
  150. tenantId = 0;
  151. }
  152. // update-begin--author:sunjianlei---date:220230428---for:【QQYUN-5279】修复分享的应用租户和当前登录租户不一致时,提示404的问题
  153. const userStore = useUserStoreWithOut();
  154. // 判断是否有临时租户id
  155. if (userStore.hasShareTenantId && userStore.shareTenantId !== 0) {
  156. // 临时租户id存在,使用临时租户id
  157. tenantId = userStore.shareTenantId!;
  158. }
  159. // update-end--author:sunjianlei---date:220230428---for:【QQYUN-5279】修复分享的应用租户和当前登录租户不一致时,提示404的问题
  160. config.headers[ConfigEnum.TENANT_ID] = tenantId;
  161. //--update-begin--author:liusq---date:20220325---for: 增加vue3标记
  162. config.headers[ConfigEnum.VERSION] = 'v3';
  163. //--update-end--author:liusq---date:20220325---for:增加vue3标记
  164. //--update-end--author:liusq---date:20211105---for:将多租户id,添加在请求接口 Header
  165. // ========================================================================================
  166. // update-begin--author:sunjianlei---date:20220624--for: 添加低代码应用ID
  167. const routeParams = router.currentRoute.value ? router.currentRoute.value.params : router.currentRoute.params;
  168. if (routeParams.appId) {
  169. config.headers[ConfigEnum.X_LOW_APP_ID] = routeParams.appId;
  170. // lowApp自定义筛选条件
  171. if (routeParams.lowAppFilter) {
  172. config.params = { ...config.params, ...JSON.parse(routeParams.lowAppFilter as string) };
  173. delete routeParams.lowAppFilter;
  174. }
  175. }
  176. // update-end--author:sunjianlei---date:20220624--for: 添加低代码应用ID
  177. // ========================================================================================
  178. }
  179. return config;
  180. },
  181. /**
  182. * @description: 响应拦截器处理
  183. */
  184. responseInterceptors: (res: AxiosResponse<any>) => {
  185. return res;
  186. },
  187. /**
  188. * @description: 响应错误处理
  189. */
  190. responseInterceptorsCatch: (error: any) => {
  191. const { t } = useI18n();
  192. const errorLogStore = useErrorLogStoreWithOut();
  193. errorLogStore.addAjaxErrorInfo(error);
  194. const { response, code, message, config } = error || {};
  195. const errorMessageMode = config?.requestOptions?.errorMessageMode || 'none';
  196. //scott 20211022 token失效提示信息
  197. //const msg: string = response?.data?.error?.message ?? '';
  198. const msg: string = response?.data?.message ?? '';
  199. const err: string = error?.toString?.() ?? '';
  200. let errMessage = '';
  201. try {
  202. if (code === 'ECONNABORTED' && message.indexOf('timeout') !== -1) {
  203. errMessage = t('sys.api.apiTimeoutMessage');
  204. }
  205. if (err?.includes('Network Error')) {
  206. errMessage = t('sys.api.networkExceptionMsg');
  207. }
  208. if (errMessage) {
  209. if (errorMessageMode === 'modal') {
  210. createErrorModal({ title: t('sys.api.errorTip'), content: errMessage });
  211. } else if (errorMessageMode === 'message') {
  212. createMessage.error(errMessage);
  213. }
  214. return Promise.reject(error);
  215. }
  216. } catch (error) {
  217. throw new Error(error);
  218. }
  219. checkStatus(error?.response?.status, msg, errorMessageMode);
  220. return Promise.reject(error);
  221. },
  222. };
  223. function createAxios(opt?: Partial<CreateAxiosOptions>) {
  224. return new VAxios(
  225. deepMerge(
  226. {
  227. // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#authentication_schemes
  228. // authentication schemes,e.g: Bearer
  229. // authenticationScheme: 'Bearer',
  230. authenticationScheme: '',
  231. timeout: 10 * 1000,
  232. // 基础接口地址
  233. // baseURL: globSetting.apiUrl,
  234. headers: { 'Content-Type': ContentTypeEnum.JSON },
  235. // 如果是form-data格式
  236. // headers: { 'Content-Type': ContentTypeEnum.FORM_URLENCODED },
  237. // 数据处理方式
  238. transform,
  239. // 配置项,下面的选项都可以在独立的接口请求中覆盖
  240. requestOptions: {
  241. // 默认将prefix 添加到url
  242. joinPrefix: true,
  243. // 是否返回原生响应头 比如:需要获取响应头时使用该属性
  244. isReturnNativeResponse: false,
  245. // 需要对返回数据进行处理
  246. isTransformResponse: true,
  247. // post请求的时候添加参数到url
  248. joinParamsToUrl: false,
  249. // 格式化提交参数时间
  250. formatDate: true,
  251. // 异常消息提示类型
  252. errorMessageMode: 'message',
  253. // 成功消息提示类型
  254. successMessageMode: 'success',
  255. // 接口地址
  256. apiUrl: globSetting.apiUrl,
  257. // 接口拼接地址
  258. urlPrefix: urlPrefix,
  259. // 是否加入时间戳
  260. joinTime: true,
  261. // 忽略重复请求
  262. ignoreCancelToken: true,
  263. // 是否携带token
  264. withToken: true,
  265. },
  266. },
  267. opt || {}
  268. )
  269. );
  270. }
  271. export const defHttp = createAxios();
  272. // other api url
  273. // export const otherHttp = createAxios({
  274. // requestOptions: {
  275. // apiUrl: 'xxx',
  276. // },
  277. // });