http.ts 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. import type { CustomRequestOptions } from '@/http/types'
  2. import { nextTick } from 'vue'
  3. import { useUserStore } from '@/store/user'
  4. // 刷新 token 状态管理
  5. let refreshing = false // 防止重复刷新 token 标识
  6. let taskQueue: (() => void)[] = [] // 刷新 token 请求队列
  7. export function http<T>(options: CustomRequestOptions) {
  8. // 1. 返回 Promise 对象
  9. return new Promise<IResData<T>>((resolve, reject) => {
  10. uni.request({
  11. ...options,
  12. dataType: 'json',
  13. // #ifndef MP-WEIXIN
  14. responseType: 'json',
  15. // #endif
  16. // 响应成功
  17. success: async (res) => {
  18. // 状态码 2xx,参考 axios 的设计
  19. if (res.statusCode >= 200 && res.statusCode < 300) {
  20. // 2.1 提取核心数据 res.data
  21. return resolve(res.data as IResData<T>)
  22. }
  23. // 原策略1: 清理用户信息,跳转到登录页
  24. else if (res.statusCode === 401) {
  25. // 401错误 -> 清理用户信息,跳转到登录页
  26. // userStore.clearUserInfo()
  27. // uni.navigateTo({ url: '/pages/login/login' })
  28. reject(res)
  29. }
  30. /* -------- 策略2:无感刷新 token ----------- */
  31. const store = useUserStore()
  32. const { refreshToken } = store.userToken || {}
  33. // token 失效的,且有刷新 token 的,才放到请求队列里
  34. const resData: IResData<T> = res.data as IResData<T>
  35. if ((res.statusCode === 401 || resData.code === 401) && refreshToken) {
  36. taskQueue.push(() => {
  37. resolve(http<T>(options))
  38. })
  39. }
  40. // 如果有 refreshToken 且未在刷新中,发起刷新 token 请求
  41. if ((res.statusCode === 401 || resData.code === 401) && refreshToken && !refreshing) {
  42. refreshing = true
  43. try {
  44. // 发起刷新 token 请求(使用 store 的 refreshToken 方法)
  45. await store.refreshToken()
  46. // 刷新 token 成功
  47. refreshing = false
  48. nextTick(() => {
  49. // 关闭其他弹窗
  50. uni.hideToast()
  51. uni.showToast({
  52. title: 'token 刷新成功',
  53. icon: 'none',
  54. })
  55. })
  56. // 将任务队列的所有任务重新请求
  57. taskQueue.forEach(task => task())
  58. }
  59. catch (refreshErr) {
  60. refreshing = false
  61. // 刷新 token 失败,跳转到登录页
  62. nextTick(() => {
  63. // 关闭其他弹窗
  64. uni.hideToast()
  65. uni.showToast({
  66. title: '登录已过期,请重新登录',
  67. icon: 'none',
  68. })
  69. })
  70. // 清除用户信息
  71. await store.logout()
  72. // 跳转到登录页
  73. setTimeout(() => {
  74. uni.navigateTo({ url: '/pages/login/login' })
  75. }, 2000)
  76. }
  77. finally {
  78. // 不管刷新 token 成功与否,都清空任务队列
  79. taskQueue = []
  80. }
  81. }
  82. else {
  83. // 其他错误 -> 根据后端错误信息轻提示
  84. !options.hideErrorToast
  85. && uni.showToast({
  86. icon: 'none',
  87. title: (res.data as IResData<T>).msg || '请求错误',
  88. })
  89. reject(res)
  90. }
  91. },
  92. // 响应失败
  93. fail(err) {
  94. uni.showToast({
  95. icon: 'none',
  96. title: '网络错误,换个网络试试',
  97. })
  98. reject(err)
  99. },
  100. })
  101. })
  102. }
  103. /**
  104. * GET 请求
  105. * @param url 后台地址
  106. * @param query 请求query参数
  107. * @param header 请求头,默认为json格式
  108. * @returns
  109. */
  110. export function httpGet<T>(url: string, query?: Record<string, any>, header?: Record<string, any>, options?: Partial<CustomRequestOptions>) {
  111. return http<T>({
  112. url,
  113. query,
  114. method: 'GET',
  115. header,
  116. ...options,
  117. })
  118. }
  119. /**
  120. * POST 请求
  121. * @param url 后台地址
  122. * @param data 请求body参数
  123. * @param query 请求query参数,post请求也支持query,很多微信接口都需要
  124. * @param header 请求头,默认为json格式
  125. * @returns
  126. */
  127. export function httpPost<T>(url: string, data?: Record<string, any>, query?: Record<string, any>, header?: Record<string, any>, options?: Partial<CustomRequestOptions>) {
  128. return http<T>({
  129. url,
  130. query,
  131. data,
  132. method: 'POST',
  133. header,
  134. ...options,
  135. })
  136. }
  137. /**
  138. * PUT 请求
  139. */
  140. export function httpPut<T>(url: string, data?: Record<string, any>, query?: Record<string, any>, header?: Record<string, any>, options?: Partial<CustomRequestOptions>) {
  141. return http<T>({
  142. url,
  143. data,
  144. query,
  145. method: 'PUT',
  146. header,
  147. ...options,
  148. })
  149. }
  150. /**
  151. * DELETE 请求(无请求体,仅 query)
  152. */
  153. export function httpDelete<T>(url: string, query?: Record<string, any>, header?: Record<string, any>, options?: Partial<CustomRequestOptions>) {
  154. return http<T>({
  155. url,
  156. query,
  157. method: 'DELETE',
  158. header,
  159. ...options,
  160. })
  161. }
  162. http.get = httpGet
  163. http.post = httpPost
  164. http.put = httpPut
  165. http.delete = httpDelete
  166. // 支持与 alovaJS 类似的API调用
  167. http.Get = httpGet
  168. http.Post = httpPost
  169. http.Put = httpPut
  170. http.Delete = httpDelete