http.ts 5.9 KB

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