You need to sign in or sign up before continuing.
request.js 2.0 KB
Newer Older
何秀钢 已提交
1 2 3 4
import axios from 'axios' // 引入axios
import { Message } from 'element-ui'
import { store } from '@/store'
import context from '@/main'
5

Mr.奇淼('s avatar
Mr.奇淼( 已提交
6
const service = axios.create({
何秀钢 已提交
7 8
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 99999
Mr.奇淼('s avatar
Mr.奇淼( 已提交
9
})
Mr.奇淼('s avatar
Mr.奇淼( 已提交
10 11 12
let acitveAxios = 0
let timer
const showLoading = () => {
何秀钢 已提交
13 14 15 16 17 18 19
  acitveAxios++
  if (timer) {
    clearTimeout(timer)
  }
  timer = setTimeout(() => {
    if (acitveAxios > 0) {
      context.$bus.emit('showLoading')
Mr.奇淼('s avatar
Mr.奇淼( 已提交
20
    }
何秀钢 已提交
21
  }, 400)
Mr.奇淼('s avatar
Mr.奇淼( 已提交
22
}
Mr.奇淼('s avatar
Mr.奇淼( 已提交
23

Mr.奇淼('s avatar
Mr.奇淼( 已提交
24
const closeLoading = () => {
何秀钢 已提交
25 26 27 28 29 30 31
  acitveAxios--
  if (acitveAxios <= 0) {
    clearTimeout(timer)
    context.$bus.emit('closeLoading')
  }
}
// http request 拦截器
Mr.奇淼('s avatar
Mr.奇淼( 已提交
32
service.interceptors.request.use(
何秀钢 已提交
33 34 35
  config => {
    if (!config.donNotShowLoading) {
      showLoading()
Mr.奇淼('s avatar
Mr.奇淼( 已提交
36
    }
何秀钢 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
    const token = store.getters['user/token']
    const user = store.getters['user/userInfo']
    config.data = JSON.stringify(config.data)
    config.headers = {
      'Content-Type': 'application/json',
      'x-token': token,
      'x-user-id': user.ID
    }
    return config
  },
  error => {
    closeLoading()
    Message({
      showClose: true,
      message: error,
      type: 'error'
    })
    return error
  }
)
Mr.奇淼('s avatar
Mr.奇淼( 已提交
57

何秀钢 已提交
58
// http response 拦截器
Mr.奇淼('s avatar
Mr.奇淼( 已提交
59
service.interceptors.response.use(
何秀钢 已提交
60 61
  response => {
    closeLoading()
62

何秀钢 已提交
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
    if (response.headers['new-token']) {
      store.commit('user/setToken', response.headers['new-token'])
    }
    if (response.data.code === 0 || response.headers.success === 'true') {
      return response.data
    } else {
      Message({
        showClose: true,
        message: response.data.msg || decodeURI(response.headers.msg),
        type: response.headers.msgtype || 'error'
      })
      if (response.data.data && response.data.data.reload) {
        store.commit('user/LoginOut')
      }
      return response.data.msg ? response.data : response
Mr.奇淼('s avatar
Mr.奇淼( 已提交
78
    }
何秀钢 已提交
79 80 81 82 83 84 85 86 87 88
  },
  error => {
    closeLoading()
    Message({
      showClose: true,
      message: error,
      type: 'error'
    })
    return error
  }
Mr.奇淼('s avatar
Mr.奇淼( 已提交
89 90
)

何秀钢 已提交
91
export default service