http.ts 5.5 KB

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