index.ts 13 KB

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