index.ts 14 KB

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