Blame view

ant-design-vue-jeecg/src/utils/request.js 6.34 KB
肖超群 authored
1
2
3
import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
肖超群 authored
4
import {VueAxios} from './axios'
肖超群 authored
5
import router from '@/router/index'
肖超群 authored
6
import {ACCESS_TOKEN, TENANT_ID} from "@/store/mutation-types"
肖超群 authored
7
8
9
10
11
12
13
14
15
16
17
18
19

/**
 * 【指定 axios baseURL
 * 如果手工指定 baseURL: '/jeecg-boot'
 * 则映射后端域名,通过 vue.config.js
 * @type {*|string}
 */
let apiBaseUrl = window._CONFIG['domianURL'] || "/jeecg-boot";
//console.log("apiBaseUrl= ",apiBaseUrl)
// 创建 axios 实例
const service = axios.create({
  //baseURL: '/jeecg-boot',
  baseURL: apiBaseUrl, // api base_url
20
  timeout: 120 * 1000 // 请求超时时间
肖超群 authored
21
22
23
24
25
26
})

const err = (error) => {
  if (error.response) {
    let data = error.response.data
    const token = Vue.ls.get(ACCESS_TOKEN)
肖超群 authored
27
28
    console.log("------异常响应------", token)
    console.log("------异常响应------", error.response.status)
肖超群 authored
29
30
    switch (error.response.status) {
      case 403:
肖超群 authored
31
        Vue.prototype.$Jnotification.error({message: '系统提示', description: '拒绝访问', duration: 4})
肖超群 authored
32
33
        break
      case 500:
肖超群 authored
34
        console.log("------error.response------", error.response)
肖超群 authored
35
        // update-begin- --- author:liusq ------ date:20200910 ---- for:处理Blob情况----
肖超群 authored
36
37
        let type = error.response.request.responseType;
        if (type === 'blob') {
肖超群 authored
38
39
40
41
          blobToJson(data);
          break;
        }
        // update-end- --- author:liusq ------ date:20200910 ---- for:处理Blob情况----
肖超群 authored
42
        if (token && data.message.includes("Token失效")) {
肖超群 authored
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
          // update-begin- --- author:scott ------ date:20190225 ---- for:Token失效采用弹框模式,不直接跳转----
          if (/wxwork|dingtalk/i.test(navigator.userAgent)) {
            Vue.prototype.$Jmessage.loading('登录已过期,正在重新登陆', 0)
          } else {
            Vue.prototype.$Jmodal.error({
              title: '登录已过期',
              content: '很抱歉,登录已过期,请重新登录',
              okText: '重新登录',
              mask: false,
              onOk: () => {
                store.dispatch('Logout').then(() => {
                  Vue.ls.remove(ACCESS_TOKEN)
                  try {
                    let path = window.document.location.pathname
                    console.log('location pathname -> ' + path)
                    if (path != '/' && path.indexOf('/user/login') == -1) {
                      window.location.reload()
                    }
                  } catch (e) {
                    window.location.reload()
                  }
                })
              }
            })
          }
          // update-end- --- author:scott ------ date:20190225 ---- for:Token失效采用弹框模式,不直接跳转----
        }
        break
      case 404:
肖超群 authored
72
        Vue.prototype.$Jnotification.error({message: '系统提示', description: '很抱歉,资源未找到!', duration: 4})
肖超群 authored
73
74
        break
      case 504:
肖超群 authored
75
        Vue.prototype.$Jnotification.error({message: '系统提示', description: '网络超时'})
肖超群 authored
76
77
        break
      case 401:
肖超群 authored
78
        Vue.prototype.$Jnotification.error({message: '系统提示', description: '很抱歉,登录已过期,请重新登录', duration: 4})
肖超群 authored
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
        if (token) {
          store.dispatch('Logout').then(() => {
            setTimeout(() => {
              window.location.reload()
            }, 1500)
          })
        }
        break
      default:
        Vue.prototype.$Jnotification.error({
          message: '系统提示',
          description: data.message,
          duration: 4
        })
        break
    }
  } else if (error.message) {
    if (error.message.includes('timeout')) {
      Vue.prototype.$Jnotification.error({message: '系统提示', description: '网络超时'})
    } else {
      Vue.prototype.$Jnotification.error({message: '系统提示', description: error.message})
    }
  }
  return Promise.reject(error)
};

// request interceptor
service.interceptors.request.use(config => {
  const token = Vue.ls.get(ACCESS_TOKEN)
  if (token) {
肖超群 authored
109
    config.headers['X-Access-Token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
肖超群 authored
110
111
112
113
114
115
116
117
118
119
120
121
122
123
  }

  // update-begin--author:sunjianlei---date:20200723---for 如果当前在low-app环境,并且携带了appId,就向Header里传递appId
  const $route = router.currentRoute
  if ($route && $route.name && $route.name.startsWith('low-app') && $route.params.appId) {
    config.headers['X-Low-App-ID'] = $route.params.appId
  }
  // update-end--author:sunjianlei---date:20200723---for 如果当前在low-app环境,并且携带了appId,就向Header里传递appId

  //update-begin-author:taoyan date:2020707 for:多租户
  let tenantid = Vue.ls.get(TENANT_ID)
  if (!tenantid) {
    tenantid = 0;
  }
肖超群 authored
124
  config.headers['tenant-id'] = tenantid
肖超群 authored
125
  //update-end-author:taoyan date:2020707 for:多租户
肖超群 authored
126
127
  if (config.method == 'get') {
    if (config.url.indexOf("sys/dict/getDictItems") < 0) {
肖超群 authored
128
      config.params = {
肖超群 authored
129
        _t: Date.parse(new Date()) / 1000,
肖超群 authored
130
131
132
133
134
        ...config.params
      }
    }
  }
  return config
肖超群 authored
135
}, (error) => {
肖超群 authored
136
137
138
139
140
  return Promise.reject(error)
})

// response interceptor
service.interceptors.response.use((response) => {
肖超群 authored
141
142
  return response.data
}, err)
肖超群 authored
143
144
145

const installer = {
  vm: {},
肖超群 authored
146
  install(Vue, router = {}) {
肖超群 authored
147
148
149
    Vue.use(VueAxios, router, service)
  }
}
肖超群 authored
150
肖超群 authored
151
152
153
154
155
156
157
/**
 * Blob解析
 * @param data
 */
function blobToJson(data) {
  let fileReader = new FileReader();
  let token = Vue.ls.get(ACCESS_TOKEN);
肖超群 authored
158
  fileReader.onload = function () {
肖超群 authored
159
160
    try {
      let jsonData = JSON.parse(this.result);  // 说明是普通对象数据,后台转换失败
肖超群 authored
161
      console.log("jsonData", jsonData)
肖超群 authored
162
      if (jsonData.status === 500) {
肖超群 authored
163
164
        console.log("token----------》", token)
        if (token && jsonData.message.includes("Token失效")) {
肖超群 authored
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
          Modal.error({
            title: '登录已过期',
            content: '很抱歉,登录已过期,请重新登录',
            okText: '重新登录',
            mask: false,
            onOk: () => {
              store.dispatch('Logout').then(() => {
                Vue.ls.remove(ACCESS_TOKEN)
                window.location.reload()
              })
            }
          })
        }
      }
    } catch (err) {
      // 解析成对象失败,说明是正常的文件流
肖超群 authored
181
      console.log("blob解析fileReader返回err", err)
肖超群 authored
182
183
184
185
186
187
188
189
190
    }
  };
  fileReader.readAsText(data)
}

export {
  installer as VueAxios,
  service as axios
}