http.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. * @returns
  48. */
  49. export const httpGet = <T>(url: string, query?: Record<string, any>) => {
  50. return http<T>({
  51. url,
  52. query,
  53. method: 'GET',
  54. })
  55. }
  56. /**
  57. * POST 请求
  58. * @param url 后台地址
  59. * @param data 请求body参数
  60. * @param query 请求query参数,post请求也支持query,很多微信接口都需要
  61. * @returns
  62. */
  63. export const httpPost = <T>(
  64. url: string,
  65. data?: Record<string, any>,
  66. query?: Record<string, any>,
  67. ) => {
  68. return http<T>({
  69. url,
  70. query,
  71. data,
  72. method: 'POST',
  73. })
  74. }
  75. http.get = httpGet
  76. http.post = httpPost