request.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /* eslint-disable no-param-reassign */
  2. import qs from 'qs'
  3. import { useUserStore } from '@/store'
  4. import { platform } from '@/utils/platform'
  5. import { getEvnBaseUrl } from '@/utils'
  6. export type CustomRequestOptions = UniApp.RequestOptions & {
  7. query?: Record<string, any>
  8. /** 出错时是否隐藏错误提示 */
  9. hideErrorToast?: boolean
  10. } & IUniUploadFileOptions // 添加uni.uploadFile参数类型
  11. // 请求基准地址
  12. const baseUrl = getEvnBaseUrl()
  13. // 拦截器配置
  14. const httpInterceptor = {
  15. // 拦截前触发
  16. invoke(options: CustomRequestOptions) {
  17. // 接口请求支持通过 query 参数配置 queryString
  18. if (options.query) {
  19. const queryStr = qs.stringify(options.query)
  20. if (options.url.includes('?')) {
  21. options.url += `&${queryStr}`
  22. } else {
  23. options.url += `?${queryStr}`
  24. }
  25. }
  26. // 非 http 开头需拼接地址
  27. if (!options.url.startsWith('http')) {
  28. // #ifdef H5
  29. // console.log(__VITE_APP_PROXY__)
  30. if (JSON.parse(__VITE_APP_PROXY__)) {
  31. // 啥都不需要做
  32. } else {
  33. options.url = baseUrl + options.url
  34. }
  35. // #endif
  36. // 非H5正常拼接
  37. // #ifndef H5
  38. options.url = baseUrl + options.url
  39. // #endif
  40. // TIPS: 如果需要对接多个后端服务,也可以在这里处理,拼接成所需要的地址
  41. }
  42. // 1. 请求超时
  43. options.timeout = 10000 // 10s
  44. // 2. (可选)添加小程序端请求头标识
  45. options.header = {
  46. platform, // 可选,与 uniapp 定义的平台一致,告诉后台来源
  47. ...options.header,
  48. }
  49. // 3. 添加 token 请求头标识
  50. const userStore = useUserStore()
  51. const { token } = userStore.userInfo as unknown as IUserInfo
  52. if (token) {
  53. options.header.Authorization = `Bearer ${token}`
  54. }
  55. },
  56. }
  57. export const requestInterceptor = {
  58. install() {
  59. // 拦截 request 请求
  60. uni.addInterceptor('request', httpInterceptor)
  61. // 拦截 uploadFile 文件上传
  62. uni.addInterceptor('uploadFile', httpInterceptor)
  63. },
  64. }