index.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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: 'https://api.shopro.sheepjs.com/',
  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. console.log(config);
  66. if (config.custom.auth && !$store('user').isLogin) {
  67. showAuthModal();
  68. return Promise.reject();
  69. }
  70. if (config.custom.showLoading) {
  71. LoadingInstance.count++;
  72. LoadingInstance.count === 1 &&
  73. uni.showLoading({
  74. title: config.custom.loadingMsg,
  75. mask: true,
  76. fail: () => {
  77. uni.hideLoading();
  78. },
  79. });
  80. }
  81. const token = uni.getStorageSync('token');
  82. if (token) config.header['Authorization'] = token;
  83. // TODO 芋艿:特殊处理
  84. if (config.url.indexOf('/app-api/') !== -1) {
  85. config.header['Accept'] = '*/*'
  86. config.header['tenant-id'] = '1';
  87. config.header['Authorization'] = 'Bearer test247';
  88. }
  89. return config;
  90. },
  91. (error) => {
  92. return Promise.reject(error);
  93. },
  94. );
  95. /**
  96. * @description 响应拦截器
  97. */
  98. http.interceptors.response.use(
  99. (response) => {
  100. // 自动设置登陆令牌
  101. if (response.header.authorization || response.header.Authorization) {
  102. $store('user').setToken(response.header.authorization || response.header.Authorization);
  103. }
  104. response.config.custom.showLoading && closeLoading();
  105. if (response.data.error !== 0) {
  106. if (response.config.custom.showError)
  107. uni.showToast({
  108. title: response.data.msg || '服务器开小差啦,请稍后再试~',
  109. icon: 'none',
  110. mask: true,
  111. });
  112. return Promise.resolve(response.data);
  113. }
  114. if (
  115. response.data.error === 0 &&
  116. response.data.msg !== '' &&
  117. response.config.custom.showSuccess
  118. ) {
  119. uni.showToast({
  120. title: response.config.custom.successMsg || response.data.msg,
  121. icon: 'none',
  122. });
  123. }
  124. return Promise.resolve(response.data);
  125. },
  126. (error) => {
  127. const userStore = $store('user');
  128. const isLogin = userStore.isLogin;
  129. let errorMessage = '网络请求出错';
  130. if (error !== undefined) {
  131. switch (error.statusCode) {
  132. case 400:
  133. errorMessage = '请求错误';
  134. break;
  135. case 401:
  136. if (isLogin) {
  137. errorMessage = '您的登陆已过期';
  138. } else {
  139. errorMessage = '请先登录';
  140. }
  141. userStore.logout(true);
  142. showAuthModal();
  143. break;
  144. case 403:
  145. errorMessage = '拒绝访问';
  146. break;
  147. case 404:
  148. errorMessage = '请求出错';
  149. break;
  150. case 408:
  151. errorMessage = '请求超时';
  152. break;
  153. case 429:
  154. errorMessage = '请求频繁, 请稍后再访问';
  155. break;
  156. case 500:
  157. errorMessage = '服务器开小差啦,请稍后再试~';
  158. break;
  159. case 501:
  160. errorMessage = '服务未实现';
  161. break;
  162. case 502:
  163. errorMessage = '网络错误';
  164. break;
  165. case 503:
  166. errorMessage = '服务不可用';
  167. break;
  168. case 504:
  169. errorMessage = '网络超时';
  170. break;
  171. case 505:
  172. errorMessage = 'HTTP版本不受支持';
  173. break;
  174. }
  175. if (error.errMsg.includes('timeout')) errorMessage = '请求超时';
  176. // #ifdef H5
  177. if (error.errMsg.includes('Network'))
  178. errorMessage = window.navigator.onLine ? '服务器异常' : '请检查您的网络连接';
  179. // #endif
  180. }
  181. if (error && error.config) {
  182. if (error.config.custom.showError === false) {
  183. uni.showToast({
  184. title: error.data?.msg || errorMessage,
  185. icon: 'none',
  186. mask: true,
  187. });
  188. }
  189. error.config.custom.showLoading && closeLoading();
  190. }
  191. return false;
  192. },
  193. );
  194. const request = (config) => {
  195. if (config.url[0] !== '/') {
  196. config.url = '/app-api/' + config.url;
  197. }
  198. // TODO 芋艿:额外拼接
  199. if (config.url.indexOf('/app-api/') >= 0) {
  200. config.url = 'http://api-dashboard.yudao.iocoder.cn' + config.url; // 调用【云端】
  201. // config.url = 'http://127.0.0.1:48080' + config.url; // 调用【本地】
  202. }
  203. return http.middleware(config);
  204. };
  205. export default request;