index.ts 15 KB

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