index.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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 {
  10. showAuthModal, cancelAutoSign
  11. } from '@/sheep/hooks/useModal';
  12. import AuthUtil from '@/sheep/api/member/auth';
  13. const options = {
  14. // 显示操作成功消息 默认不显示
  15. showSuccess: false,
  16. // 成功提醒 默认使用后端返回值
  17. successMsg: '',
  18. // 显示失败消息 默认显示
  19. showError: true,
  20. // 失败提醒 默认使用后端返回信息
  21. errorMsg: '',
  22. // 显示请求时loading模态框 默认显示
  23. showLoading: true,
  24. // loading提醒文字
  25. loadingMsg: '加载中',
  26. // 需要授权才能请求 默认放开
  27. auth: false,
  28. // ...
  29. };
  30. // Loading全局实例
  31. let LoadingInstance = {
  32. target: null,
  33. count: 0,
  34. };
  35. /**
  36. * 关闭loading
  37. */
  38. function closeLoading() {
  39. if (LoadingInstance.count > 0) LoadingInstance.count--;
  40. if (LoadingInstance.count === 0) uni.hideLoading();
  41. }
  42. /**
  43. * @description 请求基础配置 可直接使用访问自定义请求
  44. */
  45. const http = new Request({
  46. baseURL: baseUrl + apiPath,
  47. timeout: 8000,
  48. method: 'GET',
  49. header: {
  50. Accept: 'text/json',
  51. 'Content-Type': 'application/json;charset=UTF-8',
  52. platform: $platform.name,
  53. },
  54. // #ifdef APP-PLUS
  55. sslVerify: false,
  56. // #endif
  57. // #ifdef H5
  58. // 跨域请求时是否携带凭证(cookies)仅H5支持(HBuilderX 2.6.15+)
  59. withCredentials: false,
  60. // #endif
  61. custom: options,
  62. });
  63. /**
  64. * @description 请求拦截器
  65. */
  66. http.interceptors.request.use(
  67. (config) => {
  68. // 自定义处理【auth 授权】:必须登录的接口,则跳出 AuthModal 登录弹窗
  69. if (config.custom.auth && !$store('user').isLogin) {
  70. showAuthModal();
  71. return Promise.reject();
  72. }
  73. // 自定义处理【loading 加载中】:如果需要显示 loading,则显示 loading
  74. if (config.custom.showLoading) {
  75. LoadingInstance.count++;
  76. LoadingInstance.count === 1 &&
  77. uni.showLoading({
  78. title: config.custom.loadingMsg,
  79. mask: true,
  80. fail: () => {
  81. uni.hideLoading();
  82. },
  83. });
  84. }
  85. // 增加 token 令牌、terminal 终端、tenant 租户的请求头
  86. const token = getAccessToken();
  87. if (token) {
  88. config.header['Authorization'] = token;
  89. }
  90. // TODO 非繁人:特殊处理
  91. config.header['Accept'] = '*/*'
  92. config.header['tenant-id'] = '1';
  93. config.header['terminal'] = '20';
  94. // config.header['Authorization'] = 'Bearer test247';
  95. return config;
  96. },
  97. (error) => {
  98. return Promise.reject(error);
  99. },
  100. );
  101. /**
  102. * @description 响应拦截器
  103. */
  104. http.interceptors.response.use(
  105. (response) => {
  106. // 约定:如果是 /auth/ 下的 URL 地址,并且返回了 accessToken 说明是登录相关的接口,则自动设置登陆令牌
  107. if (response.config.url.indexOf('/member/auth/') >= 0 && response.data?.data?.accessToken) {
  108. console.log("设置token")
  109. $store('user').setToken(response.data.data.accessToken, response.data.data.refreshToken);
  110. }
  111. // 自定处理【loading 加载中】:如果需要显示 loading,则关闭 loading
  112. response.config.custom.showLoading && closeLoading();
  113. // 自定义处理【error 错误提示】:如果需要显示错误提示,则显示错误提示
  114. if (response.data.code !== 0) {
  115. // 特殊:如果 401 错误码,则跳转到登录页 or 刷新令牌
  116. if (response.data.code === 401) {
  117. cancelAutoSign()
  118. return refreshToken(response.config);
  119. }
  120. // 错误提示
  121. if (response.config.custom.showError) {
  122. cancelAutoSign()
  123. uni.showToast({
  124. title: response.data.msg || '服务器开小差啦,请稍后再试~',
  125. icon: 'none',
  126. mask: true,
  127. });
  128. }
  129. }
  130. // 自定义处理【showSuccess 成功提示】:如果需要显示成功提示,则显示成功提示
  131. if (response.config.custom.showSuccess
  132. && response.config.custom.successMsg !== ''
  133. && response.data.code === 0) {
  134. uni.showToast({
  135. title: response.config.custom.successMsg,
  136. icon: 'none',
  137. });
  138. }
  139. // 返回结果:包括 code + data + msg
  140. return Promise.resolve(response.data);
  141. },
  142. (error) => {
  143. console.log("服务器开小差")
  144. cancelAutoSign()
  145. const userStore = $store('user');
  146. const isLogin = userStore.isLogin;
  147. let errorMessage = '网络请求出错';
  148. if (error !== undefined) {
  149. switch (error.statusCode) {
  150. case 400:
  151. errorMessage = '请求错误';
  152. break;
  153. case 401:
  154. errorMessage = isLogin ? '您的登陆已过期' : '请登录';
  155. // 正常情况下,后端不会返回 401 错误,所以这里不处理 handleAuthorized
  156. break;
  157. case 403:
  158. errorMessage = '拒绝访问';
  159. break;
  160. case 404:
  161. errorMessage = '请求出错';
  162. break;
  163. case 408:
  164. errorMessage = '请求超时';
  165. break;
  166. case 429:
  167. errorMessage = '请求频繁, 请稍后再访问';
  168. break;
  169. case 500:
  170. errorMessage = '服务器开小差啦,请稍后再试~';
  171. break;
  172. case 501:
  173. errorMessage = '服务未实现';
  174. break;
  175. case 502:
  176. errorMessage = '网络错误';
  177. break;
  178. case 503:
  179. errorMessage = '服务不可用';
  180. break;
  181. case 504:
  182. errorMessage = '网络超时';
  183. break;
  184. case 505:
  185. errorMessage = 'HTTP 版本不受支持';
  186. break;
  187. }
  188. if (error.errMsg.includes('timeout')) errorMessage = '请求超时';
  189. // #ifdef H5
  190. if (error.errMsg.includes('Network'))
  191. errorMessage = window.navigator.onLine ? '服务器异常' : '请检查您的网络连接';
  192. // #endif
  193. }
  194. if (error && error.config) {
  195. if (error.config.custom.showError === false) {
  196. uni.showToast({
  197. title: error.data?.msg || errorMessage,
  198. icon: 'none',
  199. mask: true,
  200. });
  201. }
  202. error.config.custom.showLoading && closeLoading();
  203. }
  204. return false;
  205. },
  206. );
  207. // Axios 无感知刷新令牌,参考 https://www.dashingdog.cn/article/11 与 https://segmentfault.com/a/1190000020210980 实现
  208. let requestList = [] // 请求队列
  209. let isRefreshToken = false // 是否正在刷新中
  210. const refreshToken = async (config) => {
  211. // 如果当前已经是 refresh-token 的 URL 地址,并且还是 401 错误,说明是刷新令牌失败了,直接返回 Promise.reject(error)
  212. if (config.url.indexOf('/member/auth/refresh-token') >= 0) {
  213. return Promise.reject('error')
  214. }
  215. // 如果未认证,并且未进行刷新令牌,说明可能是访问令牌过期了
  216. if (!isRefreshToken) {
  217. isRefreshToken = true
  218. // 1. 如果获取不到刷新令牌,则只能执行登出操作
  219. const refreshToken = getRefreshToken()
  220. if (!refreshToken) {
  221. return handleAuthorized()
  222. }
  223. // 2. 进行刷新访问令牌
  224. try {
  225. const refreshTokenResult = await AuthUtil.refreshToken(refreshToken);
  226. if (refreshTokenResult.code !== 0) {
  227. // 如果刷新不成功,直接抛出 e 触发 2.2 的逻辑
  228. // noinspection ExceptionCaughtLocallyJS
  229. throw new Error('刷新令牌失败');
  230. }
  231. // 2.1 刷新成功,则回放队列的请求 + 当前请求
  232. config.header.Authorization = 'Bearer ' + getAccessToken()
  233. requestList.forEach((cb) => {
  234. cb()
  235. })
  236. requestList = []
  237. return request(config)
  238. } catch (e) {
  239. // 为什么需要 catch 异常呢?刷新失败时,请求因为 Promise.reject 触发异常。
  240. // 2.2 刷新失败,只回放队列的请求
  241. requestList.forEach((cb) => {
  242. cb()
  243. })
  244. // 提示是否要登出。即不回放当前请求!不然会形成递归
  245. return handleAuthorized()
  246. } finally {
  247. requestList = []
  248. isRefreshToken = false
  249. }
  250. } else {
  251. // 添加到队列,等待刷新获取到新的令牌
  252. return new Promise((resolve) => {
  253. requestList.push(() => {
  254. config.header.Authorization = 'Bearer ' + getAccessToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  255. resolve(request(config))
  256. })
  257. })
  258. }
  259. }
  260. /**
  261. * 处理 401 未登录的错误
  262. */
  263. const handleAuthorized = () => {
  264. const userStore = $store('user');
  265. userStore.logout(true);
  266. showAuthModal();
  267. // 登录超时
  268. return Promise.reject({
  269. code: 401,
  270. msg: userStore.isLogin ? '您的登陆已过期' : '请登录'
  271. })
  272. }
  273. /** 获得访问令牌 */
  274. const getAccessToken = () => {
  275. return uni.getStorageSync('token');
  276. }
  277. /** 获得刷新令牌 */
  278. const getRefreshToken = () => {
  279. return uni.getStorageSync('refresh-token');
  280. }
  281. const request = (config) => {
  282. return http.middleware(config);
  283. };
  284. export default request;