request.js 8.9 KB

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