index.ts 11 KB

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