request.ts 2.1 KB

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