index.js 6.2 KB

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