http.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. import { CustomRequestOptions } from '@/interceptors/request'
  2. export const http = <T>(options: CustomRequestOptions) => {
  3. // 1. 返回 Promise 对象
  4. return new Promise<IResData<T>>((resolve, reject) => {
  5. uni.request({
  6. ...options,
  7. dataType: 'json',
  8. // #ifndef MP-WEIXIN
  9. responseType: 'json',
  10. // #endif
  11. // 响应成功
  12. success(res) {
  13. // 状态码 2xx,参考 axios 的设计
  14. if (res.statusCode >= 200 && res.statusCode < 300) {
  15. // 2.1 提取核心数据 res.data
  16. resolve(res.data as IResData<T>)
  17. } else if (res.statusCode === 401) {
  18. // 401错误 -> 清理用户信息,跳转到登录页
  19. // userStore.clearUserInfo()
  20. // uni.navigateTo({ url: '/pages/login/login' })
  21. reject(res)
  22. } else {
  23. // 其他错误 -> 根据后端错误信息轻提示
  24. !options.hideErrorToast &&
  25. uni.showToast({
  26. icon: 'none',
  27. title: (res.data as IResData<T>).msg || '请求错误',
  28. })
  29. reject(res)
  30. }
  31. },
  32. // 响应失败
  33. fail(err) {
  34. uni.showToast({
  35. icon: 'none',
  36. title: '网络错误,换个网络试试',
  37. })
  38. reject(err)
  39. },
  40. })
  41. })
  42. }
  43. /**
  44. * GET 请求
  45. * @param url 后台地址
  46. * @param query 请求query参数
  47. * @param header 请求头,默认为json格式
  48. * @returns
  49. */
  50. export const httpGet = <T>(
  51. url: string,
  52. query?: Record<string, any>,
  53. header?: Record<string, any>,
  54. ) => {
  55. return http<T>({
  56. url,
  57. query,
  58. method: 'GET',
  59. header,
  60. })
  61. }
  62. /**
  63. * POST 请求
  64. * @param url 后台地址
  65. * @param data 请求body参数
  66. * @param query 请求query参数,post请求也支持query,很多微信接口都需要
  67. * @param header 请求头,默认为json格式
  68. * @returns
  69. */
  70. export const httpPost = <T>(
  71. url: string,
  72. data?: Record<string, any>,
  73. query?: Record<string, any>,
  74. header?: Record<string, any>,
  75. ) => {
  76. return http<T>({
  77. url,
  78. query,
  79. data,
  80. method: 'POST',
  81. header,
  82. })
  83. }
  84. /**
  85. * PUT 请求
  86. */
  87. export const httpPut = <T>(
  88. url: string,
  89. data?: Record<string, any>,
  90. query?: Record<string, any>,
  91. header?: Record<string, any>,
  92. ) => {
  93. return http<T>({
  94. url,
  95. data,
  96. query,
  97. method: 'PUT',
  98. header,
  99. })
  100. }
  101. /**
  102. * DELETE 请求(无请求体,仅 query)
  103. */
  104. export const httpDelete = <T>(
  105. url: string,
  106. query?: Record<string, any>,
  107. header?: Record<string, any>,
  108. ) => {
  109. return http<T>({
  110. url,
  111. query,
  112. method: 'DELETE',
  113. header,
  114. })
  115. }
  116. http.get = httpGet
  117. http.post = httpPost
  118. http.put = httpPut
  119. http.delete = httpDelete