request.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import type { IRequestOptions } from '@/models/requestTypes'
  2. import type { App } from 'vue'
  3. import { useUserStore } from '@/stores/modules/userStore'
  4. import qs from 'qs'
  5. const interceptor = {
  6. // 请求前拦截
  7. invoke(options: IRequestOptions) {
  8. const userStore = useUserStore()
  9. // api 处理
  10. options.url = `${import.meta.env.VITE_APP_BASE_API}${options.url}`
  11. // 查询参数处理
  12. if (options.query) {
  13. const query = qs.stringify(Object.assign({}, options.query), {
  14. addQueryPrefix: true,
  15. })
  16. options.url += query
  17. }
  18. // 10 秒请求超时
  19. options.timeout = 100_000
  20. // 请求头标识符
  21. const sysInfo = uni.getSystemInfoSync()
  22. options.header = {
  23. ...options.header,
  24. version: sysInfo.appVersion, // 版本号
  25. platform: sysInfo.osName ?? 'app', // 所用系统
  26. }
  27. // token
  28. if (userStore.token) {
  29. options.header.Authorization = `Bearer ${userStore.token}`
  30. }
  31. },
  32. }
  33. export function setupRequestInterceptor(app: App) {
  34. app.use({
  35. install() {
  36. uni.addInterceptor('request', interceptor)
  37. },
  38. })
  39. }