1
hejianhao
2024-12-31 4d151a9bd66df24c33d7cf35ba5c6b593f1bdf79
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import router from '@/router';
import axios from 'axios'
import store from '@/store';
 
import {
  Message
} from 'element-ui'
const service = axios.create({
  baseURL: `http://192.168.110.34:9090`,
  timeout: 30000, // request timeout
})
 
// 请求拦截
service.interceptors.request.use(
  config => {
    let token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = token;
    }
    // get
    if (config.method == 'get') {
      if (!config.params) config.params = {};
      config.params = {
        ...config.params,
      }
    }
    if (config.method == 'post') {
      // 文件上传
      if (config?.data?.blob) {
        const formData = new FormData();
        formData.append('file', config.data.blob);
        config.headers['Content-Type'] = 'multipart/form-data; boundary=----WebKitFormBoundaryfJ7Q1AjuTNDYAaad';
        config.data = formData
        return config
      }
      // 普通post
      if (!config.data) config.data = {};
      config.data = {
        ...config.data,
      }
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
 
// 响应拦截
service.interceptors.response.use(
  response => {
    return new Promise((resolve, reject) => {
      if (!response) {
        reject(new Error('请求超时'))
      }
      const res = response;
      if (res.status === 200) {
        resolve(res.data)
      } else {
        Message({
          iconClass: " ",
          customClass: "el-message--error",
          message: res.data.msg || 'Error',
          type: 'error',
          duration: 1500,
          center: true
        })
        reject(res.data)
      }
    })
  },
  error => {
    Message({
      iconClass: " ",
      customClass: "el-message--error",
      message: error.message,
      type: 'error',
      duration: 1500,
      center: true
    })
    return Promise.reject(error)
  }
)
 
export default service