request.js 9.1 KB

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