instance.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. const { token } = useUserStore()
  16. method.config.headers.Authorization = token || 'Basic c21xamgtYXBwbGV0OjEyMzQ1Ng=='
  17. // Add timestamp to prevent caching for GET requests
  18. if (method.type === 'GET' && CommonUtil.isObj(method.config.params)) {
  19. method.config.params._t = Date.now()
  20. }
  21. // Log request in development
  22. if (import.meta.env.MODE === 'development') {
  23. console.log(
  24. `[Alova Request] ${method.type} ${method.url}`,
  25. method.data || method.config.params,
  26. )
  27. // console.log(`[API Base URL] ${import.meta.env.VITE_API_BASE_URL}`);
  28. // console.log(`[Environment] ${import.meta.env.VITE_ENV_NAME}`);
  29. }
  30. console.log(
  31. BASE_URL,
  32. '=================所连服务器==========================',
  33. )
  34. },
  35. // Response handlers
  36. responded: {
  37. // Success handler
  38. onSuccess: handleAlovaResponse,
  39. // Error handler
  40. onError: handleAlovaError,
  41. // Complete handler - runs after success or error
  42. },
  43. // We'll use the middleware in the hooks
  44. // middleware is not directly supported in createAlova options
  45. // Default request timeout (10 seconds)
  46. timeout: 60000,
  47. // 设置为null即可全局关闭全部请求缓存
  48. cacheFor: null,
  49. })
  50. export default alovaInstance