http.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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. const responseData = res.data as IResponse<T>
  23. const { code } = responseData
  24. // 检查是否是401错误(包括HTTP状态码401或业务码401)
  25. const isTokenExpired = res.statusCode === 401 || code === 401
  26. if (isTokenExpired) {
  27. const tokenStore = useTokenStore()
  28. if (!isDoubleTokenMode) {
  29. // 未启用双token策略,清理用户信息,跳转到登录页
  30. tokenStore.logout()
  31. uni.navigateTo({ url: LOGIN_PAGE })
  32. return reject(res)
  33. }
  34. /* -------- 无感刷新 token ----------- */
  35. const { refreshToken } = tokenStore.tokenInfo as IDoubleTokenRes || {}
  36. // token 失效的,且有刷新 token 的,才放到请求队列里
  37. if (refreshToken) {
  38. taskQueue.push(() => {
  39. resolve(http<T>(options))
  40. })
  41. }
  42. // 如果有 refreshToken 且未在刷新中,发起刷新 token 请求
  43. if (refreshToken && !refreshing) {
  44. refreshing = true
  45. try {
  46. // 发起刷新 token 请求(使用 store 的 refreshToken 方法)
  47. await tokenStore.refreshToken()
  48. // 刷新 token 成功
  49. refreshing = false
  50. nextTick(() => {
  51. // 关闭其他弹窗
  52. uni.hideToast()
  53. uni.showToast({
  54. title: 'token 刷新成功',
  55. icon: 'none',
  56. })
  57. })
  58. // 将任务队列的所有任务重新请求
  59. taskQueue.forEach(task => task())
  60. }
  61. catch (refreshErr) {
  62. console.error('刷新 token 失败:', refreshErr)
  63. refreshing = false
  64. // 刷新 token 失败,跳转到登录页
  65. nextTick(() => {
  66. // 关闭其他弹窗
  67. uni.hideToast()
  68. uni.showToast({
  69. title: '登录已过期,请重新登录',
  70. icon: 'none',
  71. })
  72. })
  73. // 清除用户信息
  74. await tokenStore.logout()
  75. // 跳转到登录页
  76. setTimeout(() => {
  77. uni.navigateTo({ url: LOGIN_PAGE })
  78. }, 2000)
  79. }
  80. finally {
  81. // 不管刷新 token 成功与否,都清空任务队列
  82. taskQueue = []
  83. }
  84. }
  85. return reject(res)
  86. }
  87. // 处理其他成功状态(HTTP状态码200-299)
  88. if (res.statusCode >= 200 && res.statusCode < 300) {
  89. // 处理业务逻辑错误
  90. if (code !== ResultEnum.Success0 && code !== ResultEnum.Success200) {
  91. uni.showToast({
  92. icon: 'none',
  93. title: responseData.msg || responseData.message || '请求错误',
  94. })
  95. //这里不直接抛出错误,会中断promise链条,无法进入finally,在下方return resolve(responseData as T)继续执行,在接口调用可通过判断code来处理业务逻辑
  96. //async getSampleEnums() {
  97. // const res = await getSampleEnumsApi();
  98. // if (res.code === ResultEnum.Success200) {
  99. // // 处理成功
  100. // }
  101. //},
  102. //throw new Error(`请求错误[${code}]:${responseData.message || responseData.msg}`)
  103. }
  104. return resolve(responseData as T)
  105. }
  106. // 处理其他错误
  107. !options.hideErrorToast
  108. && uni.showToast({
  109. icon: 'none',
  110. title: (res.data as any).msg || '请求错误',
  111. })
  112. reject(res)
  113. },
  114. // 响应失败
  115. fail(err) {
  116. uni.showToast({
  117. icon: 'none',
  118. title: '网络错误,换个网络试试',
  119. })
  120. reject(err)
  121. },
  122. })
  123. })
  124. }
  125. /**
  126. * GET 请求
  127. * @param url 后台地址
  128. * @param query 请求query参数
  129. * @param header 请求头,默认为json格式
  130. * @returns
  131. */
  132. export function httpGet<T>(url: string, query?: Record<string, any>, header?: Record<string, any>, options?: Partial<CustomRequestOptions>) {
  133. return http<T>({
  134. url,
  135. query,
  136. method: 'GET',
  137. header,
  138. ...options,
  139. })
  140. }
  141. /**
  142. * POST 请求
  143. * @param url 后台地址
  144. * @param data 请求body参数
  145. * @param query 请求query参数,post请求也支持query,很多微信接口都需要
  146. * @param header 请求头,默认为json格式
  147. * @returns
  148. */
  149. export function httpPost<T>(url: string, data?: Record<string, any>, query?: Record<string, any>, header?: Record<string, any>, options?: Partial<CustomRequestOptions>) {
  150. return http<T>({
  151. url,
  152. query,
  153. data,
  154. method: 'POST',
  155. header,
  156. ...options,
  157. })
  158. }
  159. /**
  160. * PUT 请求
  161. */
  162. export function httpPut<T>(url: string, data?: Record<string, any>, query?: Record<string, any>, header?: Record<string, any>, options?: Partial<CustomRequestOptions>) {
  163. return http<T>({
  164. url,
  165. data,
  166. query,
  167. method: 'PUT',
  168. header,
  169. ...options,
  170. })
  171. }
  172. /**
  173. * DELETE 请求(无请求体,仅 query)
  174. */
  175. export function httpDelete<T>(url: string, query?: Record<string, any>, header?: Record<string, any>, options?: Partial<CustomRequestOptions>) {
  176. return http<T>({
  177. url,
  178. query,
  179. method: 'DELETE',
  180. header,
  181. ...options,
  182. })
  183. }
  184. // 支持与 axios 类似的API调用
  185. http.get = httpGet
  186. http.post = httpPost
  187. http.put = httpPut
  188. http.delete = httpDelete
  189. // 支持与 alovaJS 类似的API调用
  190. http.Get = httpGet
  191. http.Post = httpPost
  192. http.Put = httpPut
  193. http.Delete = httpDelete