request.js 8.9 KB

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