http.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /* eslint-disable no-param-reassign */
  2. import { useUserStore } from '@/store'
  3. import { UserInfo } from '@/typings'
  4. import { translate as t } from '@/locales/index'
  5. type Data<T> = {
  6. code: number
  7. msg: string
  8. result: T
  9. }
  10. uni.showModal({
  11. title: '菲鸽',
  12. content: t('app.name'),
  13. })
  14. // 请求基地址
  15. const baseURL = import.meta.env.VITE_SERVER_BASEURL
  16. // console.log(import.meta.env)
  17. // 拦截器配置
  18. const httpInterceptor = {
  19. // 拦截前触发
  20. invoke(options: UniApp.RequestOptions) {
  21. // 1. 非 http 开头需拼接地址
  22. if (!options.url.startsWith('http')) {
  23. options.url = baseURL + options.url
  24. }
  25. // 2. 请求超时
  26. options.timeout = 10000 // 10s
  27. // 3. 添加小程序端请求头标识
  28. options.header = {
  29. platform: 'mp-weixin', // 可选值与 uniapp 定义的平台一致,告诉后台来源
  30. ...options.header,
  31. }
  32. // 4. 添加 token 请求头标识
  33. const userStore = useUserStore()
  34. const { token } = userStore.userInfo as unknown as UserInfo
  35. if (token) {
  36. options.header.Authorization = `Bearer ${token}`
  37. }
  38. },
  39. }
  40. // 拦截 request 请求
  41. uni.addInterceptor('request', httpInterceptor)
  42. // 拦截 uploadFile 文件上传
  43. uni.addInterceptor('uploadFile', httpInterceptor)
  44. export const http = <T>(options: UniApp.RequestOptions) => {
  45. // 1. 返回 Promise 对象
  46. return new Promise<Data<T>>((resolve, reject) => {
  47. uni.request({
  48. ...options,
  49. // 响应成功
  50. success(res) {
  51. // 状态码 2xx,参考 axios 的设计
  52. if (res.statusCode >= 200 && res.statusCode < 300) {
  53. // 2.1 提取核心数据 res.data
  54. resolve(res.data as Data<T>)
  55. } else if (res.statusCode === 401) {
  56. // 401错误 -> 清理用户信息,跳转到登录页
  57. // userStore.clearUserInfo()
  58. // uni.navigateTo({ url: '/pages/login/login' })
  59. reject(res)
  60. } else {
  61. // 其他错误 -> 根据后端错误信息轻提示
  62. uni.showToast({
  63. icon: 'none',
  64. title: (res.data as Data<T>).msg || '请求错误',
  65. })
  66. reject(res)
  67. }
  68. },
  69. // 响应失败
  70. fail(err) {
  71. uni.showToast({
  72. icon: 'none',
  73. title: '网络错误,换个网络试试',
  74. })
  75. reject(err)
  76. },
  77. })
  78. })
  79. }
  80. export default http