http.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import { CustomRequestOptions } from '@/interceptors/request'
  2. import type { IResData } from '@/typings'
  3. import NProgress from '@/utils/nprogress'
  4. import { SmCrypto } from '@/utils/crypto'
  5. const smCrypto = new SmCrypto(import.meta.env.VITE_PRIVATE_KEY, import.meta.env.VITE_PUBLIC_KEY)
  6. export const http = <T>(options: CustomRequestOptions) => {
  7. let resdata = options.data
  8. console.info('🚀 ~ 请求数据', resdata)
  9. options.data = smCrypto.doEncrypt(options.data)
  10. NProgress.start()
  11. // 1. 返回 Promise 对象
  12. return new Promise<IResData<T>>((resolve, reject) => {
  13. // console.log('当前语言:', uni.getStorageSync('lang'))
  14. uni.request({
  15. ...options,
  16. header: {
  17. Authorization: `Bearer ${uni.getStorageSync('token')}` || '',
  18. lang: uni.getStorageSync('lang') || 'en',
  19. },
  20. timeout: 50000,
  21. //
  22. dataType: 'json',
  23. // #ifndef MP-WEIXIN
  24. responseType: 'json',
  25. // #endif
  26. // 响应成功
  27. success(res) {
  28. console.log('返回数据', res)
  29. res.data = smCrypto.doDecrypt(res.data)
  30. NProgress.done()
  31. // 状态码 2xx,参考 axios 的设计
  32. if (res.statusCode >= 200 && res.statusCode < 300) {
  33. // 2.1 提取核心数据 res.data
  34. resolve(res.data as IResData<T>)
  35. } else if (res.statusCode === 401) {
  36. // 401错误 -> 清理用户信息,跳转到登录页
  37. // userStore.clearUserInfo()
  38. // uni.navigateTo({ url: '/pages/login/login' })
  39. reject(res)
  40. } else {
  41. // 其他错误 -> 根据后端错误信息轻提示
  42. !options.hideErrorToast &&
  43. uni.showToast({
  44. icon: 'none',
  45. title: (res.data as IResData<T>).msg || 'inter error',
  46. })
  47. reject(res)
  48. }
  49. },
  50. // 响应失败
  51. fail(err) {
  52. NProgress.done()
  53. uni.showToast({
  54. icon: 'none',
  55. title: 'inter error please try again',
  56. })
  57. reject(err)
  58. },
  59. })
  60. })
  61. }
  62. /**
  63. * GET 请求
  64. * @param url 后台地址
  65. * @param query 请求query参数
  66. * @returns
  67. */
  68. export const httpGet = <T>(url: string, query?: Record<string, any>) => {
  69. return http<T>({
  70. url,
  71. query,
  72. method: 'GET',
  73. })
  74. }
  75. /**
  76. * POST 请求
  77. * @param url 后台地址
  78. * @param data 请求body参数
  79. * @param query 请求query参数,post请求也支持query,很多微信接口都需要
  80. * @returns
  81. */
  82. export const httpPost = <T>(
  83. url: string,
  84. data?: Record<string, any>,
  85. query?: Record<string, any>,
  86. ) => {
  87. return http<T>({
  88. url,
  89. query,
  90. data,
  91. method: 'POST',
  92. })
  93. }
  94. http.get = httpGet
  95. http.post = httpPost