instance.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import AdapterUniapp from '@alova/adapter-uniapp'
  2. import { createAlova } from 'alova'
  3. import vueHook from 'alova/vue'
  4. import { handleAlovaError, handleAlovaResponse } from './handlers'
  5. import { BASE_URL } from '@/config'
  6. export const alovaInstance = createAlova({
  7. baseURL: BASE_URL,
  8. ...AdapterUniapp(),
  9. statesHook: vueHook,
  10. beforeRequest: (method) => {
  11. // Add content type for POST/PUT/PATCH requests
  12. if (['POST', 'PUT', 'PATCH'].includes(method.type)) {
  13. method.config.headers['Content-Type'] = 'application/json'
  14. }
  15. // if (['POST', 'PUT', 'PATCH', 'DELETE', 'GET'].includes(method.type)) {
  16. // method.config.headers['X-Tenant-Domain'] = BASE_URL
  17. // }
  18. const { token } = useUserStore()
  19. method.config.headers.Authorization = token || 'Basic c21xamgtYXBwbGV0OjEyMzQ1Ng=='
  20. // Add timestamp to prevent caching for GET requests
  21. if (method.type === 'GET' && CommonUtil.isObj(method.config.params)) {
  22. method.config.params._t = Date.now()
  23. }
  24. // Log request in development
  25. if (import.meta.env.MODE === 'development') {
  26. console.log(
  27. `[Alova Request] ${method.type} ${method.url}`,
  28. method.data || method.config.params,
  29. )
  30. // console.log(`[API Base URL] ${import.meta.env.VITE_API_BASE_URL}`);
  31. // console.log(`[Environment] ${import.meta.env.VITE_ENV_NAME}`);
  32. }
  33. console.log(
  34. BASE_URL,
  35. '=================所连服务器==========================',
  36. )
  37. },
  38. // Response handlers
  39. responded: {
  40. // Success handler
  41. onSuccess: handleAlovaResponse,
  42. // Error handler
  43. onError: handleAlovaError,
  44. // Complete handler - runs after success or error
  45. },
  46. // We'll use the middleware in the hooks
  47. // middleware is not directly supported in createAlova options
  48. // Default request timeout (10 seconds)
  49. timeout: 60000,
  50. // 设置为null即可全局关闭全部请求缓存
  51. cacheFor: null,
  52. })
  53. export default alovaInstance