1
hejianhao
2025-01-09 8db5f9ecd73d19d06f09ce9ef460f3a5d6c8192d
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
86
87
88
89
90
91
import axios from 'axios'
import CryptoJS from 'crypto-js';
import apiConfig from '@/config/baseurl'
import store from '@/store'
 
import {
  Message
} from 'element-ui'
 
 
const service = axios.create({
  baseURL: apiConfig.baseURL,
  withCredentials: false, // 当跨域请求时发送cookie
  timeout: 30000, // request timeout
})
 
// 请求拦截
service.interceptors.request.use(
  config => {
    const env = process.env.NODE_ENV; //development  production
    let { url } = config;
    if (env === 'production') {
      url = url.replace(/.$/, '0');
      config.url = url;
    } else {
      url = url.replace(/.$/, '1');
      config.url = url;
    }
 
    const nowTime = Date.now()
    const sign = CryptoJS.HmacSHA1(nowTime, apiConfig.secretKEY).toString(CryptoJS.enc.Base64)
 
    config['headers']['timestamp'] = nowTime
    config['headers']['sign'] = sign
    if (config.method == 'get') {
      if (!config.params) config.params = {};
      config.params = {
        ...config.params,
      }
    }
    if (config.method == 'post') {
      if (!config.data) config.data = {};
      config.data = {
        ...config.data,
      }
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
 
// 响应拦截
service.interceptors.response.use(
  response => {
    if (!response) {
      return
    }
    const res = response;
    if (res.data.status == 0) {
      if (!res.data) {
        return Promise.resolve({})
      }
      return Promise.resolve(res.data)
    } else {
      if (res.data.status == 103 || res.data.status == 401) {
        Message({
          message: res.data.msg || '登录已过期,请重新登录',
          type: 'warning',
          duration: 2000
        })
        store.commit('SET_USERINFO', {})
        store.commit('SET_USERNAME', '')
        localStorage.clear()
        window.location.replace('/');
        return Promise.reject(res.data)
      }
      Message({
        message: res.data.msg || '服务器错误',
        type: 'error',
        duration: 2000
      })
      return Promise.reject(res.data)
    }
  },
  error => {
    return Promise.reject(error.message)
  }
)
export default service