interceptor.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import type { CustomRequestOptions } from '@/http/types'
  2. import { useTokenStore } from '@/store'
  3. import { getEnvBaseUrl } from '@/utils'
  4. import { platform } from '@/utils/platform'
  5. import { stringifyQuery } from './tools/queryString'
  6. // 请求基准地址
  7. const baseUrl = getEnvBaseUrl()
  8. // 拦截器配置
  9. const httpInterceptor = {
  10. // 拦截前触发
  11. invoke(options: CustomRequestOptions) {
  12. // 接口请求支持通过 query 参数配置 queryString
  13. if (options.query) {
  14. const queryStr = stringifyQuery(options.query)
  15. if (options.url.includes('?')) {
  16. options.url += `&${queryStr}`
  17. }
  18. else {
  19. options.url += `?${queryStr}`
  20. }
  21. }
  22. // 非 http 开头需拼接地址
  23. if (!options.url.startsWith('http')) {
  24. // #ifdef H5
  25. // console.log(__VITE_APP_PROXY__)
  26. if (JSON.parse(__VITE_APP_PROXY__)) {
  27. // 自动拼接代理前缀
  28. options.url = import.meta.env.VITE_APP_PROXY_PREFIX + options.url
  29. }
  30. else {
  31. options.url = baseUrl + options.url
  32. }
  33. // #endif
  34. // 非H5正常拼接
  35. // #ifndef H5
  36. options.url = baseUrl + options.url
  37. // #endif
  38. // TIPS: 如果需要对接多个后端服务,也可以在这里处理,拼接成所需要的地址
  39. }
  40. // 1. 请求超时
  41. options.timeout = 60000 // 60s
  42. // 2. (可选)添加小程序端请求头标识
  43. options.header = {
  44. platform, // 可选,与 uniapp 定义的平台一致,告诉后台来源
  45. ...options.header,
  46. }
  47. // 3. 添加 token 请求头标识
  48. const tokenStore = useTokenStore()
  49. const token = tokenStore.validToken
  50. if (token) {
  51. options.header.Authorization = `Bearer ${token}`
  52. }
  53. },
  54. }
  55. export const requestInterceptor = {
  56. install() {
  57. // 拦截 request 请求
  58. uni.addInterceptor('request', httpInterceptor)
  59. // 拦截 uploadFile 文件上传
  60. uni.addInterceptor('uploadFile', httpInterceptor)
  61. },
  62. }