request.ts 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. import config from '@/config';
  2. import { useInfoStore } from '@/store';
  3. import { getCurrentPage } from '@/utils/public';
  4. import { recursiveDecodeURIComponent } from '@/utils/ruoyi';
  5. import errorCode from '@/utils/errorCode';
  6. const { clientId, appid } = config;
  7. // uniapp封装的请求方法
  8. let timeout = 60 * 1000;
  9. // 获取全局请求头方法
  10. const getHeader = () => {
  11. let header = {
  12. 'Content-Type': 'application/json',
  13. Authorization: 'Bearer ' + useInfoStore().token || '',
  14. xid: config?.appid || '',
  15. clientId: config?.clientId || '',
  16. };
  17. return header;
  18. };
  19. // 获取host地址
  20. export const request = ({ url, method = 'GET', data = {}, isToken = true, header = null }: any) => {
  21. const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000';
  22. if (isToken && useInfoStore().isTokenExpired()) {
  23. uni.hideLoading();
  24. useInfoStore().removeToken();
  25. let fullPath = recursiveDecodeURIComponent(getCurrentPage()?.$page?.fullPath);
  26. const isLoginPage = recursiveDecodeURIComponent(fullPath)?.indexOf('/pages/login/login') !== -1;
  27. if (isLoginPage) {
  28. return;
  29. }
  30. const fulllpathParams = fullPath.split('?');
  31. const fullpathstr = fulllpathParams.length > 1 ? `${fulllpathParams[0]}?${fulllpathParams[fulllpathParams.length - 1]}` : fulllpathParams[0];
  32. // 获取当前页面路径
  33. uni.$u.route({
  34. type: 'redirect',
  35. url: '/pages/login/login',
  36. params: {
  37. // 转成浏览器可识别的字符串
  38. // 这里可以传递当前页面的路径作为参数,方便登录后重定向回原页面
  39. redirect: encodeURIComponent(fullpathstr),
  40. },
  41. });
  42. return;
  43. }
  44. return new Promise((resolve, reject) => {
  45. uni.request({
  46. url: baseUrl + url,
  47. method,
  48. data,
  49. timeout: timeout,
  50. header: header || getHeader(),
  51. })
  52. .then((response) => {
  53. let { data, statusCode } = response;
  54. if (statusCode !== 200) {
  55. uni.showToast({
  56. icon: 'none',
  57. title: '后端接口连接异常',
  58. });
  59. reject('后端接口连接异常');
  60. return;
  61. }
  62. const code = (data as any).code || 200;
  63. const msg = errorCode[code] || (data as any).msg || errorCode['default'];
  64. // 处理业务错误
  65. if (code === 401) {
  66. uni.hideLoading();
  67. useInfoStore().removeToken();
  68. let fullPath = recursiveDecodeURIComponent(getCurrentPage()?.$page?.fullPath);
  69. const isLoginPage = recursiveDecodeURIComponent(fullPath).indexOf('/pages/login/login') !== -1;
  70. if (isLoginPage) {
  71. return;
  72. }
  73. const fulllpathParams = fullPath.split('?');
  74. const fullpathstr = fulllpathParams.length > 1 ? `${fulllpathParams[0]}?${fulllpathParams[fulllpathParams.length - 1]}` : fulllpathParams[0];
  75. // 获取当前页面路径
  76. uni.$u.route({
  77. type: 'redirect',
  78. url: '/pages/login/login',
  79. params: {
  80. // 转成浏览器可识别的字符串
  81. // 这里可以传递当前页面的路径作为参数,方便登录后重定向回原页面
  82. redirect: encodeURIComponent(fullpathstr),
  83. },
  84. });
  85. return reject('无效的会话,或者会话已过期,请重新登录。');
  86. } else if (code === 500) {
  87. uni.hideLoading();
  88. if (msg) {
  89. uni.showToast({
  90. title: msg,
  91. icon: 'none',
  92. });
  93. }
  94. return reject(data);
  95. } else if (code !== 200) {
  96. uni.hideLoading();
  97. uni.showToast({
  98. title: msg,
  99. icon: 'none',
  100. });
  101. reject(code);
  102. }
  103. // 成功情况
  104. resolve(data);
  105. })
  106. .catch((error) => {
  107. let { message } = error;
  108. if (message === 'Network Error') {
  109. message = '后端接口连接异常';
  110. } else if (message.includes('timeout')) {
  111. message = '系统接口请求超时';
  112. } else if (message.includes('Request failed with status code')) {
  113. message = '系统接口' + message.substr(message.length - 3) + '异常';
  114. }
  115. uni.hideLoading();
  116. uni.showToast({
  117. title: message,
  118. icon: 'none',
  119. });
  120. return reject(error);
  121. });
  122. });
  123. };
  124. export const useClientRequest = {
  125. post: <T = any>(url: string, data?: any, isToken?: boolean): Promise<T> => {
  126. return request({
  127. url,
  128. method: 'POST',
  129. data,
  130. isToken,
  131. }) as Promise<T>;
  132. },
  133. get: <T = any>(url: string, data?: any, isToken?: boolean): Promise<T> => {
  134. return request({
  135. url,
  136. method: 'GET',
  137. data,
  138. isToken,
  139. }) as Promise<T>;
  140. },
  141. put: <T = any>(url: string, data?: any, isToken?: boolean): Promise<T> => {
  142. return request({
  143. url,
  144. method: 'PUT',
  145. data,
  146. isToken,
  147. }) as Promise<T>;
  148. },
  149. delete: <T = any>(url: string, data?: any, isToken?: boolean): Promise<T> => {
  150. return request({
  151. url,
  152. method: 'DELETE',
  153. data,
  154. isToken,
  155. }) as Promise<T>;
  156. },
  157. };