http.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. header: Object.assign(
  8. {
  9. token: `${uni.getStorageSync('loginInfo')?.token}`,
  10. },
  11. options.header,
  12. ),
  13. dataType: 'json',
  14. // #ifndef MP-WEIXIN
  15. responseType: 'json',
  16. // #endif
  17. // 响应成功
  18. success(res) {
  19. // 状态码 2xx,参考 axios 的设计
  20. if (res.statusCode >= 200 && res.statusCode < 300) {
  21. // 2.1 提取核心数据 res.data
  22. resolve(res.data as IResData<T>)
  23. } else if (res.statusCode === 401) {
  24. // 401错误 -> 清理用户信息,跳转到登录页
  25. // userStore.clearUserInfo()
  26. // uni.navigateTo({ url: '/pages/login/login' })
  27. reject(res)
  28. } else {
  29. // 其他错误 -> 根据后端错误信息轻提示
  30. !options.hideErrorToast &&
  31. uni.showToast({
  32. icon: 'none',
  33. title: (res.data as IResData<T>).msg || '请求错误',
  34. })
  35. reject(res)
  36. }
  37. },
  38. // 响应失败
  39. fail(err) {
  40. uni.showToast({
  41. icon: 'none',
  42. title: '网络错误,换个网络试试',
  43. })
  44. reject(err)
  45. },
  46. })
  47. })
  48. }
  49. /**
  50. * GET 请求
  51. * @param url 后台地址
  52. * @param query 请求query参数
  53. * @returns
  54. */
  55. export const httpGet = <T>(url: string, query?: Record<string, any>) => {
  56. return http<T>({
  57. url,
  58. query,
  59. method: 'GET',
  60. })
  61. }
  62. /**
  63. * POST 请求
  64. * @param url 后台地址
  65. * @param data 请求body参数
  66. * @param query 请求query参数,post请求也支持query,很多微信接口都需要
  67. * @returns
  68. */
  69. export const httpPost = <T>(
  70. url: string,
  71. data?: Record<string, any>,
  72. query?: Record<string, any>,
  73. ) => {
  74. return http<T>({
  75. url,
  76. query,
  77. data,
  78. method: 'POST',
  79. })
  80. }
  81. http.get = httpGet
  82. http.post = httpPost