huang
2025-10-22 78d73df2f8e0c6855d65eb1f2c6df08e0f99bab1
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
import axios from 'axios'
import useUserInfoStore from '@/stores/userInfo'
import { host, WebSocketHost } from '@/utils/constants'
const userStore = useUserInfoStore()
const request = axios.create({
   baseURL: `http://${WebSocketHost}:${host}/api`, // 注意!! 这里是全局统一加上了 后端接口前缀 前缀,后端必须进行跨域配置!
   timeout: 30000
})
//
// request 拦截器
// 可以自请求发送前对请求做一些处理
// 比如统一加token,对请求参数统一加密
request.interceptors.request.use(config => {
   config.headers['Content-Type'] = 'application/json;charset=utf-8';
   if (userStore.user) {
      config.headers['token'] = userStore.user.token;
   }
   // 设置请求头
   // 从localStorage获取当前语言,映射为标准标识
   const lang = localStorage.getItem('lang') || 'zh' // 默认中文
   // 语言映射表:前端存储的标识 → 后端识别的标准Locale标识
   const langMap = {
      'zh': 'zh-CN',   // 中文 → 对应后端zh_CN
      'en': 'en-US',   // 英文 → 对应后端en_US
      'py': 'ru-RU'    // 俄语 → 对应后端ru_RU
   }
   config.headers['Accept-Language'] = langMap[lang] || 'zh-CN' // 默认中文
 
   return config
}, error => {
   return Promise.reject(error)
});
// response 拦截器
// 可以在接口响应后统一处理结果
request.interceptors.response.use(
   response => {
      let res = response.data;
      // 如果是返回的文件
      if (response.config.responseType === 'blob') {
         return res
      }
      // 兼容服务端返回的字符串数据
      if (typeof res === 'string') {
         res = res ? JSON.parse(res) : res
      }
      return res;
   },
   error => {
      return Promise.reject(error)
   }
)
export default request