http.ts 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. import { useMemberStore } from '@/stores'
  2. import { Decrypt, Encrypt } from './utils'
  3. import { userLoginApi } from '@/services/home'
  4. //引入 pinia 。。登录后将信息储存到pinia
  5. const baseUrl = import.meta.env.VITE_SERVE
  6. export const imgUrl = `${import.meta.env.VITE_IMG_URL}/file/show?filePath=`
  7. export const mediaUrl = `${import.meta.env.VITE_MEDIA}/file/show?filePath=`
  8. let temp_request: any[] = [],
  9. is_freshing = false
  10. const httpInterceptor = {
  11. //拦截前触发
  12. invoke(options: UniApp.RequestOptions) {
  13. //拼接地址
  14. if (!options.url.startsWith('http')) {
  15. options.url = baseUrl + options.url
  16. }
  17. //请求时间
  18. options.timeout = 10000
  19. options.header = {
  20. ...options.header,
  21. 'source-client': 'miniapp',
  22. }
  23. //判断如果请求体里有data//且data不为空
  24. if ('data' in options) {
  25. //如果包含data属性
  26. options.data = { data: Encrypt(JSON.stringify(options.data)) }
  27. }
  28. console.log(options)
  29. //添加 token 请求头标识
  30. const memberStore = useMemberStore()
  31. // const token = memberStore.profile?.token
  32. const token = memberStore.token
  33. options.header.Authorization = token ? `Bearer ${token}` : ''
  34. },
  35. }
  36. uni.addInterceptor('request', httpInterceptor)
  37. uni.addInterceptor('uploadFile', httpInterceptor)
  38. // export default baseUrl
  39. //请求函数
  40. /**
  41. * @param UniApp.RequestOptions
  42. * @returns Promise
  43. */
  44. interface Data<T> {
  45. code: string
  46. msg: string
  47. data: T
  48. }
  49. export const http = <T>(option: UniApp.RequestOptions) => {
  50. uni.showLoading()
  51. let params_ = option
  52. // console.log(option?.data)
  53. return new Promise<Data<T>>((resolve, reject) => {
  54. uni.request({
  55. ...option,
  56. success(res) {
  57. //获取状态码
  58. // res.ststusCode
  59. if (res.statusCode >= 200 && res.statusCode < 300) {
  60. //访问成功
  61. // eslint-disable-next-line no-debugger
  62. resolve(JSON.parse(Decrypt(res.data)))
  63. // resolve(res.data as Data<T>)
  64. } else if (res.statusCode === 401) {
  65. //当token过期后弹出确认再次登录的提示框
  66. //如果点击确定再次调用登录接口
  67. if (!is_freshing) {
  68. //调用登录接口
  69. refresh()
  70. } else {
  71. resolve(
  72. new Promise((resol) => {
  73. temp_request.push(() => {
  74. resol(http(params_))
  75. })
  76. }),
  77. )
  78. }
  79. //清理用户信息
  80. //跳转到登录页
  81. const memberStore = useMemberStore()
  82. memberStore.clearProfile()
  83. uni.navigateTo({
  84. url: '/src/pages/index/index',
  85. })
  86. reject(res)
  87. } else {
  88. // (res.data as Data<T>).msg
  89. uni.showToast({
  90. icon: 'none',
  91. title: (res.data as Data<T>).msg || '请求错误请稍后再试',
  92. })
  93. reject(res)
  94. }
  95. },
  96. //响应失败,网络断开
  97. fail(err) {
  98. console.log(err)
  99. uni.showToast({
  100. icon: 'none',
  101. title: '网络错误',
  102. })
  103. //网络错误
  104. },
  105. complete() {
  106. uni.hideLoading({
  107. noConflict: true,
  108. })
  109. },
  110. })
  111. })
  112. }
  113. const refresh = () => {
  114. is_freshing = true
  115. uni.login({
  116. success: (res) => {
  117. if (res.errMsg === 'login:ok') {
  118. //调用登录接口
  119. //获取到code后
  120. loginHttp(res.code)
  121. }
  122. },
  123. })
  124. }
  125. const loginHttp = async (code: string) => {
  126. const res = await userLoginApi({ code: code })
  127. //登录成功后需要将 is_refresh 状态改为false
  128. //然后回调
  129. if (res.data) {
  130. console.log(res.data)
  131. } else {
  132. is_freshing = false
  133. temp_request.map((cb) => cb())
  134. // 清空temp_request
  135. temp_request = []
  136. }
  137. }