request.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. console.log(error, '响应拦截器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 = '请先登录'
  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 440:
  179. errorMessage = '网络请求出错'; // 签名异常
  180. break;
  181. case 500:
  182. errorMessage = '服务器开小差啦,请稍后再试~';
  183. break;
  184. case 501:
  185. errorMessage = '服务未实现';
  186. break;
  187. case 502:
  188. errorMessage = '网络错误';
  189. break;
  190. case 503:
  191. errorMessage = '服务不可用';
  192. break;
  193. case 504:
  194. errorMessage = '网络超时';
  195. break;
  196. case 505:
  197. errorMessage = 'HTTP 版本不受支持';
  198. break;
  199. }
  200. if (error?.errMsg?.includes('timeout')) errorMessage = '请求超时';
  201. // #ifdef H5
  202. if (error?.errMsg?.includes('Network'))
  203. errorMessage = window.navigator.onLine ? '服务器异常' : '请检查您的网络连接';
  204. // #endif
  205. }
  206. if (error && error.config) {
  207. if (error.config.custom.showError === false) {
  208. uni.showToast({
  209. title: error.data?.error || errorMessage,
  210. icon: 'none',
  211. duration: 2000,
  212. mask: true,
  213. });
  214. }
  215. error.config.custom.showLoading && closeLoading();
  216. }
  217. return Promise.reject(error.data)
  218. },
  219. );
  220. // Axios 无感知刷新令牌,参考 https://www.dashingdog.cn/article/11 与 https://segmentfault.com/a/1190000020210980 实现
  221. let requestList = [] // 请求队列
  222. let isRefreshToken = false // 是否正在刷新中
  223. const handleRefreshToken = async (config) => {
  224. // 如果当前已经是 refresh-token 的 URL 地址,并且还是 401 错误,说明是刷新令牌失败了,直接返回 Promise.reject(error)
  225. if (config.url.indexOf('/menduner/system/auth/refresh-token') >= 0) {
  226. return Promise.reject('error')
  227. }
  228. // 如果未认证,并且未进行刷新令牌,说明可能是访问令牌过期了
  229. if (!isRefreshToken) {
  230. isRefreshToken = true
  231. // 1. 如果获取不到刷新令牌,则只能执行登出操作
  232. const refresh_token = getRefreshToken()
  233. if (!refresh_token) {
  234. return handleAuthorized()
  235. }
  236. // 2. 进行刷新访问令牌
  237. try {
  238. const refreshTokenResult = await refreshToken(refresh_token);
  239. if (refreshTokenResult.code !== 0) {
  240. // 如果刷新不成功,直接抛出 e 触发 2.2 的逻辑
  241. // noinspection ExceptionCaughtLocallyJS
  242. throw new Error('刷新令牌失败');
  243. }
  244. // 2.1 刷新成功,则回放队列的请求 + 当前请求
  245. config.header.Authorization = 'Bearer ' + getAccessToken()
  246. requestList.forEach((cb) => {
  247. cb()
  248. })
  249. requestList = []
  250. return request(config)
  251. } catch (e) {
  252. // 为什么需要 catch 异常呢?刷新失败时,请求因为 Promise.reject 触发异常。
  253. // 2.2 刷新失败,只回放队列的请求
  254. requestList.forEach((cb) => {
  255. cb()
  256. })
  257. // 提示是否要登出。即不回放当前请求!不然会形成递归
  258. return handleAuthorized()
  259. } finally {
  260. requestList = []
  261. isRefreshToken = false
  262. }
  263. } else {
  264. // 添加到队列,等待刷新获取到新的令牌
  265. return new Promise((resolve) => {
  266. requestList.push(() => {
  267. config.header.Authorization = 'Bearer ' + getAccessToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  268. resolve(request(config))
  269. })
  270. })
  271. }
  272. }
  273. /**
  274. * 处理 401 未登录的错误
  275. */
  276. const handleAuthorized = () => {
  277. const useUserStore = userStore()
  278. useUserStore.handleLogout(true);
  279. uni.showToast({
  280. title:'请先登录',
  281. duration: 2000,
  282. icon: 'none'
  283. })
  284. const msg = useUserStore.isLogin ? '您的登陆已过期' : '请先登录'
  285. useUserStore.setLogin(false)
  286. showAuthModal()
  287. // 登录超时
  288. return Promise.reject({
  289. code: 401,
  290. msg
  291. })
  292. }
  293. /** 获得访问令牌 */
  294. export const getAccessToken = () => {
  295. return uni.getStorageSync('token');
  296. }
  297. /** 获得刷新令牌 */
  298. const getRefreshToken = () => {
  299. return uni.getStorageSync('refresh-token');
  300. }
  301. const request = (config) => {
  302. return http.middleware(config);
  303. };
  304. export default request;