zhongshujie
2024-11-19 253b3f50df303f24fdf880797619432f8b74db21
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
import axios from 'axios'
import myConfig from '@/assets/js/config.js'
// import toolClass from '@/assets/js/toolClass.js'
// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_API_URL,
  timeout: myConfig.requestTimeOut // 请求超时时间
})
 
// 请求拦截器
service.interceptors.request.use(
  (config) => {
    let token = localStorage.getItem(myConfig.tokenKey)
    if (token) config.headers['Authorization'] = `bearer ${token}`
    return config
  },
  (error) => {
    // 发送失败
    Promise.reject(error)
  }
)
 
// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // dataAxios 是 axios 返回数据中的 data
    const dataAxios = response.data
    if (typeof dataAxios.data === 'boolean') {
      return dataAxios.data
    }
    if (response.config.responseType == 'blob') {
      return dataAxios
    }
    const { success } = dataAxios
    if (dataAxios.currentDate) {
      sessionStorage.currentDate = new Date(dataAxios.currentDate).getTime()
    }
    // 根据 code 进行判断
    if (success) {
      return dataAxios.data ? dataAxios.data : dataAxios
    } else {
      // 提示错误
    }
  },
  (error) => {
    if (error.response && error.response.status == 401) {
      localStorage.removeItem(myConfig.tokenKey)
      console.log(error.response);
    } else {
      if (error.response && error.response.data && error.response.data.error) {
        console.error(error.response.data.error.msg)
      } else {
        console.error('请求发生错误')
      }
    }
    return Promise.reject(error)
  }
)
 
export default service