index.js 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. /**
  2. * Shopro-request
  3. * @description api模块管理,loading配置,请求拦截,错误处理
  4. */
  5. import Request from 'luch-request';
  6. import { baseUrl, apiPath } from '@/sheep/config';
  7. import $store from '@/sheep/store';
  8. import $platform from '@/sheep/platform';
  9. import { showAuthModal } from '@/sheep/hooks/useModal';
  10. const options = {
  11. // 显示操作成功消息 默认不显示
  12. showSuccess: false,
  13. // 成功提醒 默认使用后端返回值
  14. successMsg: '',
  15. // 显示失败消息 默认显示
  16. showError: true,
  17. // 失败提醒 默认使用后端返回信息
  18. errorMsg: '',
  19. // 显示请求时loading模态框 默认显示
  20. showLoading: true,
  21. // loading提醒文字
  22. loadingMsg: '加载中',
  23. // 需要授权才能请求 默认放开
  24. auth: false,
  25. // ...
  26. };
  27. // Loading全局实例
  28. let LoadingInstance = {
  29. target: null,
  30. count: 0,
  31. };
  32. /**
  33. * 关闭loading
  34. */
  35. function closeLoading() {
  36. if (LoadingInstance.count > 0) LoadingInstance.count--;
  37. if (LoadingInstance.count === 0) uni.hideLoading();
  38. }
  39. /**
  40. * @description 请求基础配置 可直接使用访问自定义请求
  41. */
  42. const http = new Request({
  43. baseURL: baseUrl,
  44. timeout: 8000,
  45. method: 'GET',
  46. header: {
  47. Accept: 'text/json',
  48. 'Content-Type': 'application/json;charset=UTF-8',
  49. platform: $platform.name,
  50. },
  51. // #ifdef APP-PLUS
  52. sslVerify: false,
  53. // #endif
  54. // #ifdef H5
  55. // 跨域请求时是否携带凭证(cookies)仅H5支持(HBuilderX 2.6.15+)
  56. withCredentials: false,
  57. // #endif
  58. custom: options,
  59. });
  60. /**
  61. * @description 请求拦截器
  62. */
  63. http.interceptors.request.use(
  64. (config) => {
  65. if (config.custom.auth && !$store('user').isLogin) {
  66. showAuthModal();
  67. return Promise.reject();
  68. }
  69. if (config.custom.showLoading) {
  70. LoadingInstance.count++;
  71. LoadingInstance.count === 1 &&
  72. uni.showLoading({
  73. title: config.custom.loadingMsg,
  74. mask: true,
  75. fail: () => {
  76. uni.hideLoading();
  77. },
  78. });
  79. }
  80. const token = uni.getStorageSync('token');
  81. if (token) config.header['Authorization'] = token;
  82. // TODO 芋艿:特殊处理
  83. if (config.url.indexOf('/app-api/') !== -1) {
  84. config.header['Accept'] = '*/*'
  85. config.header['tenant-id'] = '1';
  86. config.header['Authorization'] = 'Bearer test247';
  87. }
  88. return config;
  89. },
  90. (error) => {
  91. return Promise.reject(error);
  92. },
  93. );
  94. /**
  95. * @description 响应拦截器
  96. */
  97. http.interceptors.response.use(
  98. (response) => {
  99. // 自动设置登陆令牌
  100. if (response.header.authorization || response.header.Authorization) {
  101. $store('user').setToken(response.header.authorization || response.header.Authorization);
  102. }
  103. response.config.custom.showLoading && closeLoading();
  104. if (response.data.error !== 0) {
  105. if (response.config.custom.showError)
  106. uni.showToast({
  107. title: response.data.msg || '服务器开小差啦,请稍后再试~',
  108. icon: 'none',
  109. mask: true,
  110. });
  111. return Promise.resolve(response.data);
  112. }
  113. if (
  114. response.data.error === 0 &&
  115. response.data.msg !== '' &&
  116. response.config.custom.showSuccess
  117. ) {
  118. uni.showToast({
  119. title: response.config.custom.successMsg || response.data.msg,
  120. icon: 'none',
  121. });
  122. }
  123. return Promise.resolve(response.data);
  124. },
  125. (error) => {
  126. const userStore = $store('user');
  127. const isLogin = userStore.isLogin;
  128. let errorMessage = '网络请求出错';
  129. if (error !== undefined) {
  130. switch (error.statusCode) {
  131. case 400:
  132. errorMessage = '请求错误';
  133. break;
  134. case 401:
  135. if (isLogin) {
  136. errorMessage = '您的登陆已过期';
  137. } else {
  138. errorMessage = '请先登录';
  139. }
  140. userStore.logout(true);
  141. showAuthModal();
  142. break;
  143. case 403:
  144. errorMessage = '拒绝访问';
  145. break;
  146. case 404:
  147. errorMessage = '请求出错';
  148. break;
  149. case 408:
  150. errorMessage = '请求超时';
  151. break;
  152. case 429:
  153. errorMessage = '请求频繁, 请稍后再访问';
  154. break;
  155. case 500:
  156. errorMessage = '服务器开小差啦,请稍后再试~';
  157. break;
  158. case 501:
  159. errorMessage = '服务未实现';
  160. break;
  161. case 502:
  162. errorMessage = '网络错误';
  163. break;
  164. case 503:
  165. errorMessage = '服务不可用';
  166. break;
  167. case 504:
  168. errorMessage = '网络超时';
  169. break;
  170. case 505:
  171. errorMessage = 'HTTP版本不受支持';
  172. break;
  173. }
  174. if (error.errMsg.includes('timeout')) errorMessage = '请求超时';
  175. // #ifdef H5
  176. if (error.errMsg.includes('Network'))
  177. errorMessage = window.navigator.onLine ? '服务器异常' : '请检查您的网络连接';
  178. // #endif
  179. }
  180. if (error && error.config) {
  181. if (error.config.custom.showError === false) {
  182. uni.showToast({
  183. title: error.data?.msg || errorMessage,
  184. icon: 'none',
  185. mask: true,
  186. });
  187. }
  188. error.config.custom.showLoading && closeLoading();
  189. }
  190. return false;
  191. },
  192. );
  193. const request = (config) => {
  194. if (config.url[0] !== '/') {
  195. config.url = apiPath + config.url;
  196. }
  197. // TODO 芋艿:额外拼接
  198. if (config.url.indexOf('/app-api/') >= 0) {
  199. config.url = 'http://api-dashboard.yudao.iocoder.cn' + config.url; // 调用【云端】
  200. // config.url = 'http://127.0.0.1:48080' + config.url; // 调用【本地】
  201. }
  202. return http.middleware(config);
  203. };
  204. export default request;