p-honggang.li
5 天以前 751dfe21d19a22bb130a6a14857470868d7be53a
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import axios, { AxiosPromise, Method } from 'axios'
import type { AxiosRequestConfig } from 'axios'
import { ElLoading, LoadingOptions, ElNotification } from 'element-plus'
import router from '@/router/index'
import { close, start } from '@/utils/nprogress' // 页面加载进度条
import { useUserInfo } from '@/stores/modules/userInfo'
const default_login_URL = import.meta.env.VITE_BASE_LOGIN_URL as string;
 
const userInfoStore = useUserInfo()
 
const pendingMap = new Map() //当前所有请求的唯一key值集合
const loadingInstance: LoadingInstance = {
  target: null,
  count: 0,
}
 
export const getUrl = (): string => {
  const value: string = import.meta.env.VITE_BASE_PATH as string
  return value
}
export const getUrlPort = (): string => {
  let url = getUrl()
  return new URL(url).port
}
 
const noTokenUrlList: [string | undefined] = ['/authentication/admin/login'] // 不需要传递token的接口请求路径集合
 
/*
 * 创建Axios
 * 默认开启`reductDataFormat(简洁响应)`,返回类型为`ApiPromise`
 * 关闭`reductDataFormat`,返回类型则为`AxiosPromise`
 */
function createAxios(
  axiosConfig: AxiosRequestConfig,
  options: Options = {},
  loading: LoadingOptions = {}
): ApiPromise | AxiosPromise {
  const Axios = axios.create({
    baseURL: getUrl(),
    timeout: 1000 * 300,
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
    },
    method: 'post',
  })
  options = Object.assign(
    {
      CancelDuplicateRequest: false, //是否开启取消重复请求,默认true
      loading: false, //是否开启页面级loading层效果,默认false
      reductDataFormat: true, //是否开启简洁的数据结构响应,默认true
      showErrorMessage: true, //是否开启接口错误信息提示,默认true
      showCodeMessage: true, //是否开启code不为0时的信息提示,默认true
      showSuccessMessage: false, // 是否开启code为0时的信息提示, 默认为false
    },
    options
  )
  /* 请求拦截 */
  Axios.interceptors.request.use(
    (config) => {
      removePending(config)
      options.CancelDuplicateRequest && addPending(config)
      // 创建loading实例
      if (options.loading) {
        loadingInstance.count++
        if (loadingInstance.count === 1) {
          loadingInstance.target = ElLoading.service(loading)
        }
      }
      // 进度条加载
      start()
      //自动携带token
      if (config.headers) {
        if (!noTokenUrlList.includes(config.url)) {
          // 从状态管理器获取token数据
          config.headers['token'] = userInfoStore.getAdminToken
          if (localStorage.getItem('lastRecordTime')) {
            config.headers["lastRecordTime"] = localStorage.getItem('lastRecordTime') as string;
          }
          config.headers["nowTime"] = new Date().getTime();
          console.log('nowTime',config.headers["nowTime"])
        }
      }
      return config
    },
    (error) => {
      return Promise.reject(error)
    }
  )
  /* 响应拦截 */
  Axios.interceptors.response.use(
    (response) => {
      removePending(response.config)
      options.loading && closeLoading(options) // 关闭loading
      // 关闭进度条
      close()
      const { config } = response
      // 下载文件 数据流格式特殊处理
      if (config.url?.includes('common/filePreview')) {
        return response
      }
      const isFile = response.headers['content-type'] === 'application/octet-stream'
      if(isFile) {
        return response
      }
      if (response.data && response.data.code == 200) {
        return response.data
      } else {
        if (response.data.code == 401) {
          userInfoStore.removeToken()
          // 跳到扫码登录
          // window.location.href=default_login_URL
          router.replace({
            path: '/login',
          })
          // window.location.href = 'http://36.139.126.109:7089/loginDem'
        } else {
          ElNotification({
            type: 'error',
            message:
              response.data.msg ||
              response.data.message ||
              response.data.errmsg,
          })
        }
        return response.data
      }
    },
    (error) => {
      error.config && removePending(error.config)
      options.loading && closeLoading(options) // 关闭loading
      // 关闭进度条
      close()
      options.showErrorMessage && httpErrorStatusHandle(error) // 处理错误状态码
      return Promise.reject(error) // 错误继续返回给到具体页面
    }
  )
  return Axios(axiosConfig)
}
 
export default createAxios
 
/**
 * 处理异常
 * @param {*} error
 */
function httpErrorStatusHandle(error: any) {
  if (axios.isCancel(error)) return console.error(error.message)
  let message = ''
  if (error && error.response) {
    switch (error.response.status) {
      case 302:
        message = '接口重定向了!'
        break
      case 400:
        message = '参数不正确!'
        break
      case 401:
        message = '您未登录,或者登录已经超时,请先登录!'
        break
      case 403:
        message = '您没有权限操作!'
        break
      case 404:
        message = `请求地址出错: ${error.response.config.url}`
        break // 在正确域名下
      case 408:
        message = '请求超时!'
        break
      case 409:
        message = '系统已存在相同数据!'
        break
      case 500:
        message = '服务器内部错误!'
        break
      case 501:
        message = '服务未实现!'
        break
      case 502:
        message = '网关错误!'
        break
      case 503:
        message = '服务不可用!'
        break
      case 504:
        message = '服务暂时无法访问,请稍后再试!'
        break
      case 505:
        message = 'HTTP版本不受支持!'
        break
      default:
        message = '异常问题,请联系管理员!'
        break
    }
  }
  if (error.message.includes('timeout')) message = '网络请求超时!'
  if (error.message.includes('Network'))
    message = window.navigator.onLine ? '服务端异常!' : '您断网了!'
 
  ElNotification({
    type: 'error',
    message,
  })
}
 
// export function requestPayload(method: Method, data: anyObj) {
//     if (method.toUpperCase() == 'GET') {
//         return {
//             params: data
//         }
//     } else if (method.toUpperCase() == 'POST') {
//         return {
//             data: data
//         }
//     }
// }
/**
 * 关闭Loading层实例
 */
function closeLoading(options: Options) {
  if (options.loading && loadingInstance.count > 0) loadingInstance.count--
  if (loadingInstance.count === 0) {
    loadingInstance.target.close()
    loadingInstance.target = null
  }
}
 
/**
 * 储存每个请求的唯一cancel回调, 以此为标识
 */
function addPending(config: AxiosRequestConfig) {
  const pendingKey = getPendingKey(config)
  config.cancelToken =
    config.cancelToken ||
    new axios.CancelToken((cancel) => {
      if (!pendingMap.has(pendingKey)) {
        pendingMap.set(pendingKey, cancel)
      }
    })
}
 
/**
 * 删除重复的请求
 */
function removePending(config: AxiosRequestConfig) {
  const pendingKey = getPendingKey(config)
  // console.log('pendingMap', pendingMap)
  if (pendingMap.has(pendingKey)) {
    const cancelToken = pendingMap.get(pendingKey)
    cancelToken(pendingKey)
    pendingMap.delete(pendingKey)
  }
}
 
/**
 * 生成每个请求的唯一key
 */
function getPendingKey(config: AxiosRequestConfig) {
  let { url, method, data, headers } = config
  // if (typeof data === 'string') data = JSON.parse(data) // response里面返回的config.data是个字符串对象
  return [
    url,
    method,
    //后面根据业务再加
    // headers && headers.batoken ? headers.batoken : '',
    // headers && headers['ba-user-token'] ? headers['ba-user-token'] : '',
    // JSON.stringify(params),
    JSON.stringify(data),
  ].join('&')
}
 
interface LoadingInstance {
  target: any
  count: number
}
 
interface Options {
  // 是否开启取消重复请求, 默认为 true
  CancelDuplicateRequest?: boolean
  // 是否开启loading层效果, 默认为false
  loading?: boolean
  // 是否开启简洁的数据结构响应, 默认为true
  reductDataFormat?: boolean
  // 是否开启接口错误信息展示,默认为true
  showErrorMessage?: boolean
  // 是否开启code不为0时的信息提示, 默认为true
  showCodeMessage?: boolean
  // 是否开启code为0时的信息提示, 默认为false
  showSuccessMessage?: boolean
}
 
// 1、接口请求返回值 code 值 定义
// 2、get请求 post请求 Content-type 分别是什么
// 3、错误返回message,前端弹出