interceptor.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import type { CustomRequestOptions } from '@/http/types'
  2. import { useTokenStore } from '@/store'
  3. import { getEnvBaseUrl } from '@/utils'
  4. import { stringifyQuery } from './tools/queryString'
  5. // 请求基准地址
  6. const baseUrl = getEnvBaseUrl()
  7. // 拦截器配置
  8. const httpInterceptor = {
  9. // 拦截前触发
  10. invoke(options: CustomRequestOptions) {
  11. // 如果您使用了alova,则请把下面的代码放开注释
  12. // alova 执行流程:alova beforeRequest --> 本拦截器 --> alova responded
  13. return options
  14. // 非 alova 请求,正常执行
  15. // 接口请求支持通过 query 参数配置 queryString
  16. if (options.query) {
  17. const queryStr = stringifyQuery(options.query)
  18. if (options.url.includes('?')) {
  19. options.url += `&${queryStr}`
  20. }
  21. else {
  22. options.url += `?${queryStr}`
  23. }
  24. }
  25. // 非 http 开头需拼接地址
  26. if (!options.url.startsWith('http')) {
  27. // #ifdef H5
  28. if (JSON.parse(import.meta.env.VITE_APP_PROXY_ENABLE)) {
  29. // 自动拼接代理前缀
  30. options.url = import.meta.env.VITE_APP_PROXY_PREFIX + options.url
  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 = 60000 // 60s
  44. // 2. (可选)添加小程序端请求头标识
  45. options.header = {
  46. ...options.header,
  47. }
  48. // 3. 添加 token 请求头标识
  49. const tokenStore = useTokenStore()
  50. const token = tokenStore.validToken
  51. if (token) {
  52. options.header['X-Access-Token'] = `${token}`
  53. options.header.AppType = '7'
  54. }
  55. return options
  56. },
  57. }
  58. export const requestInterceptor = {
  59. install() {
  60. // 拦截 request 请求
  61. uni.addInterceptor('request', httpInterceptor)
  62. // 拦截 uploadFile 文件上传
  63. uni.addInterceptor('uploadFile', httpInterceptor)
  64. },
  65. }