longz
2026-06-29 9d4cbff7464ebfd7803c2ce53ded49d0f73fe011
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import AdapterUniapp from '@alova/adapter-uniapp'
import { createAlova } from 'alova'
import vueHook from 'alova/vue'
import mockAdapter from '../mock/mockAdapter'
import { handleAlovaError, handleAlovaResponse } from './handlers'
import { getPersistedToken } from '@/store/auth'
 
export const alovaInstance = createAlova({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  ...AdapterUniapp({
    mockRequest: mockAdapter,
  }),
  statesHook: vueHook,
  beforeRequest: (method) => {
    method.config.headers = method.config.headers || {}
    ;(method.config as Record<string, any>).header = (method.config as Record<string, any>).header || {}
 
    // Add content type for POST/PUT/PATCH requests
    if (['POST', 'PUT', 'PATCH'].includes(method.type)) {
      method.config.headers['Content-Type'] = 'application/json'
      ;(method.config as Record<string, any>).header['Content-Type'] = 'application/json'
    }
 
    // Add timestamp to prevent caching for GET requests
    if (method.type === 'GET' && CommonUtil.isObj(method.config.params)) {
      method.config.params._t = Date.now()
    }
 
    const token = getPersistedToken()
    if (token) {
      method.config.headers['Mini-Authorization'] = token
      ;(method.config as Record<string, any>).header['Mini-Authorization'] = token
    }
 
    // Log request in development
    if (import.meta.env.MODE === 'development') {
      console.log(`[Alova Request] ${method.type} ${method.url}`, method.data || method.config.params)
      console.log(`[API Base URL] ${import.meta.env.VITE_API_BASE_URL}`)
      console.log(`[Environment] ${import.meta.env.VITE_ENV_NAME}`)
    }
  },
 
  // Response handlers
  responded: {
    // Success handler
    onSuccess: handleAlovaResponse,
 
    // Error handler
    onError: handleAlovaError,
 
    // Complete handler - runs after success or error
    onComplete: async () => {
      // Any cleanup or logging can be done here
    },
  },
 
  // We'll use the middleware in the hooks
  // middleware is not directly supported in createAlova options
 
  // Default request timeout (10 seconds)
  timeout: 60000,
  // 设置为null即可全局关闭全部请求缓存
  cacheFor: null,
})
 
export default alovaInstance