request.ts 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. import axios from 'axios';
  2. import {uniqueSlash} from './urlUtils';
  3. import type {AxiosRequestConfig} from 'axios';
  4. import {ACCESS_TOKEN_KEY} from '@/enums/cacheEnum';
  5. import {Storage} from '@/utils/Storage';
  6. import {useUserStore} from '@/store/modules/user';
  7. import {alertController} from "@ionic/vue";
  8. // import {ExclamationCircleOutlined} from '@ant-design/icons'
  9. export interface RequestOptions {
  10. /** 当前接口权限, 不需要鉴权的接口请忽略, 格式:sys:user:add */
  11. permCode?: string;
  12. /** 是否直接获取data,而忽略message等 */
  13. isGetDataDirectly?: boolean;
  14. /** 请求成功是提示信息 */
  15. successMsg?: string;
  16. /** 请求失败是提示信息 */
  17. errorMsg?: string;
  18. /** 是否mock数据请求 */
  19. isMock?: boolean;
  20. /** 是否开发后台数据 */
  21. isNew?: boolean;
  22. isShowSuccessMsg?:boolean;
  23. isShowErrorMsg?:boolean;
  24. }
  25. export interface RequsetData {
  26. item: any;
  27. extdata?: any;
  28. success?: boolean;
  29. msg?: string;
  30. }
  31. const UNKNOWN_ERROR = '未知错误,请重试';
  32. // 是否生产环境
  33. // const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV);
  34. /** 真实请求的路径前缀 */
  35. const baseApiUrl = '/api/';
  36. /** mock请求路径前缀 */
  37. const baseMockUrl = '/';
  38. const service = axios.create({
  39. // baseURL: baseApiUrl,
  40. timeout: 120000,
  41. });
  42. service.interceptors.request.use(
  43. (config) => {
  44. const token = Storage.get(ACCESS_TOKEN_KEY);
  45. if (token && config.headers) {
  46. // 请求头token信息,请根据实际情况进行修改
  47. config.headers['Authorization'] = token;
  48. }
  49. return config;
  50. },
  51. (error) => {
  52. Promise.reject(error);
  53. },
  54. );
  55. service.interceptors.response.use(
  56. (response) => {
  57. const res = response.data;
  58. // if the custom code is not 200, it is judged as an error.
  59. if (res.code !== "200") {
  60. //$message.error(res.message || UNKNOWN_ERROR);
  61. // Illegal token
  62. if (res.code === 11001 || res.code === 11002) {
  63. window.localStorage.clear();
  64. window.location.reload();
  65. // to re-login
  66. // Modal.confirm({
  67. // title: '警告',
  68. // content: res.message || '账号异常,您可以取消停留在该页上,或重新登录',
  69. // okText: '重新登录',
  70. // cancelText: '取消',
  71. // onOk: () => {
  72. // localStorage.clear();
  73. // window.location.reload();
  74. // }
  75. // });
  76. }
  77. // throw other
  78. const error = new Error(res.message || res.msg || UNKNOWN_ERROR) as Error & { code: any,data:any };
  79. error.code = res.code;
  80. error.data=res.data;
  81. return Promise.reject(error);
  82. } else {
  83. return res;
  84. }
  85. },
  86. (error) => {
  87. // 处理 422 或者 500 的错误异常提示
  88. const errMsg = error?.response?.data?.message ?? UNKNOWN_ERROR;
  89. //$message.error(errMsg);
  90. error.message = errMsg;
  91. return Promise.reject(error);
  92. },
  93. );
  94. export type Response<T = any> = {
  95. code: number;
  96. message: string;
  97. data: T;
  98. };
  99. export type BaseResponse<T = any> = Promise<Response<T>>;
  100. /**
  101. *
  102. * @param method - request methods
  103. * @param url - request url
  104. * @param data - request data or params
  105. */
  106. export const request = async <T = any>(
  107. config: AxiosRequestConfig,
  108. options: RequestOptions = {},
  109. ): Promise<T> => {
  110. try {
  111. const {successMsg, errorMsg, permCode, isMock, isGetDataDirectly = true,isShowSuccessMsg = true} = options;
  112. // 如果当前是需要鉴权的接口 并且没有权限的话 则终止请求发起 , isNew
  113. if (permCode && !useUserStore().perms.includes(permCode)) {
  114. //return $message.error('你没有访问该接口的权限,请联系管理员!');
  115. return Promise.reject('你没有访问该接口的权限,请联系管理员!');
  116. }
  117. let fullUrl = '';
  118. fullUrl = `${(isMock ? baseMockUrl : baseApiUrl) + config.url}`;
  119. /*
  120. if (isNew) {
  121. fullUrl = `/n-api/${config.url}`;
  122. } else {
  123. fullUrl = `${(isMock ? baseMockUrl : baseApiUrl) + config.url}`;
  124. }*/
  125. config.url = uniqueSlash(fullUrl);
  126. // if (IS_PROD) {
  127. // // 保持api请求的协议与当前访问的站点协议一致
  128. // config.url.replace(/^https?:/g, location.protocol);
  129. // }
  130. const res = await service.request(config);
  131. successMsg && isShowSuccessMsg && presentAlert("成功",successMsg);
  132. //successMsg && $message.success(successMsg);
  133. //errorMsg && $message.error(errorMsg);
  134. return isGetDataDirectly ? res.data : res;
  135. } catch (error: any) {
  136. const {errorMsg,isShowErrorMsg=true} = options;
  137. isShowErrorMsg && presentAlert("错误",(errorMsg|| "")+error.message);
  138. return Promise.reject(error);
  139. }
  140. };
  141. const presentAlert = async (title:string,message: string) => {
  142. const alert = await alertController.create({
  143. header: title,
  144. message: message,
  145. buttons: [
  146. '确定'
  147. ],
  148. });
  149. await alert.present();
  150. }