request.js 8.6 KB

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