import Vue from 'vue'
import axios from 'axios'
import router from '@/router'
import merge from 'lodash/merge'
import {clearLoginInfo} from '@/utils'
import {
  Message,
  Loading,
  MessageBox
} from 'element-ui'

let CancelToken = axios.CancelToken
// 超时时间
axios.defaults.timeout = 60000
// 跨域请求,允许保存cookie
axios.defaults.withCredentials = true
axios.defaults.headers = {'Content-Type': 'application/json; charset=utf-8'}
// 非生产环境 && 开启代理, 接口前缀统一使用[/caseRecord]前缀做代理拦截!
const BASE_URL = process.env.NODE_ENV !== 'production' && process.env.OPEN_PROXY ? '/caseRecord' : window.SITE_CONFIG.baseUrl
// 对面暴露的基础请求路径
axios.BASE_URL = BASE_URL

/**
 * 请求拦截
 */
let loading
axios.interceptors.request.use(config => {
  console.log(this)
  let showLoading = true
  if (config.loading === false) {
    showLoading = false
  }
  if (showLoading && !config.hideloading) {
    loading = Loading.service({
      text: config.loadtext || '加载中...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
  }
  // 请求头带上token
  config.headers['token'] = Vue.cookie.get('token')
  if (config.url.indexOf('.html') > -1) {
    config.headers['Content-Type'] = 'text/html;charset=utf-8'
  }
  if (config.isFormData) {
    config.headers['Content-Type'] = 'multipart/form-data'
  }
  // 请求地址处理
  if (config.rest) {
    config.url = config.url
  } else if (config.face) {
    config.url = (window.SITE_CONFIG.mode == 1 ? window.SITE_CONFIG.faceUrl : window.SITE_CONFIG.faceVideoUrl) + config.url
  } else {
    if (config.url.indexOf('tb/ajxx') > -1) {
      config.url = window.SITE_CONFIG.baseVideoUrl + '/rest' + config.url
    } else {
      config.url = BASE_URL + config.url
    }
  }
  if (config.rest) {
    
    if (config.url.indexOf(SITE_CONFIG.vrUrl) > -1 || config.url.indexOf(SITE_CONFIG.yctsblUrl) > -1 || config.url.indexOf(SITE_CONFIG.orderJailUrl) > -1 || config.url.indexOf(SITE_CONFIG.wsMb) > -1 || config.url.indexOf(SITE_CONFIG.Msxs) > -1) {
      delete config.headers['token']
    }
  }
  let type = config.method
  let defaults = {}
  if (type === 'post') {
    // post请求参数处理
    // json: 'application/json; charset=utf-8'
    // form: 'application/x-www-form-urlencoded; charset=utf-8'
    config.data = config.isFormData ? config.data : JSON.stringify(config.data)
  } else if (type === 'get') {
    // get请求参数处理
    config.params = merge(defaults, config.params)
  }
  return config
})

/**
 * 响应拦截
 */
axios.interceptors.response.use(response => {
  if (loading) {
    loading.close()
  }
  console.log(response)
  if (response.data instanceof Blob) {
    return response.data
  }
  let serverV = response.headers['yba-version']
  let ybaV = window.localStorage.getItem('yba-version')
  if (serverV) {
    if (!ybaV) {
      window.localStorage.setItem('yba-version', serverV)
      MessageBox.alert('检测到系统版本已更新,即将为您刷新界面', {
        confirmButtonText: '确定',
        callback: action => {
          let ourl = window.location.href
          location.reload()
        }
      })
    } else {
      if (serverV != ybaV) {
        window.localStorage.setItem('yba-version', serverV)
        // 提示用户刷新
        MessageBox.alert('检测到系统版本已更新,即将为您刷新界面', {
          confirmButtonText: '确定',
          callback: action => {
            let ourl = window.location.href
            location.reload()
          }
        })
      }
    }
  }
  if (typeof response.data === 'string' && response.data.indexOf('html') > -1) {
    response.data = {
      code: 0,
      msg: 'success',
      data: response.data
    }
    return response
  } else if (response.config.url.indexOf(window.SITE_CONFIG.yctsblUrl) > -1) {
    response.data = {
      code: 0,
      msg: 'success',
      data: response.data.data
    }
    return response
  } else {
    if (response.data && response.data.code === 401) { // 401, token失效
      if (window.self == window.top) {
        clearLoginInfo()
        router.push({name: 'login'})
      }
    }
    var flag = !(response.data && (response.data.code == 0 || response.data.code == '0000'))
    if (window.SITE_CONFIG['mode'] === 2) {
      flag = !(response.data && response.data.code == '0000')
    }
    if (response.config.url.indexOf('detectFaces') > -1 || response.config.url.indexOf('detectText') > -1 || response.config.url.indexOf(SITE_CONFIG.vrUrl) > -1) {
      flag = false
    }
    console.log(flag)
    if (flag) {
      var msg = response.data.msg || response.data.result || response.data.message
      if (response.data.msg && !response.data.message) {
        response.data.message = response.data.msg
      }
      console.log(msg)
      console.log(9999)
      // if (msg.indexOf('{') > -1 && msg.indexOf('}') > -1) {
      //   msg = JSON.parse(msg).result || JSON.parse(msg).msg
      // }
      if (!response.config.notip) { // 不需要提示的情况 就在请求中加notip
        Message({
          message: msg,
          type: 'error',
          showClose: true,
          dangerouslyUseHTMLString: true,
          duration: 3000
        })
      }
    }
    return response
  }
}, error => {
  if (loading) {
    loading.close()
  }
  console.log(error)
  if (error && typeof error === 'string') {
    return Promise.reject(error)
  }
  // if(error&&typeof error == "object"&&error.response){
  if (error.response.status && error.response.status === 404) { // 401, token失效
    Message({
      message: '接口不存在',
      type: 'error',
      showClose: true,
      duration: 3000
    })
  } else if (error.response.status && (error.response.status === 408 || error.response.status === 409)) { // 401, token失效
    if (error.response.status == 409 && error.response.data.code == '401') {
      if (window.self == window.top) {
        clearLoginInfo()
        router.push({name: 'login'})
      }
    }
    var msg = error.response.data.result || error.response.data.msg || error.response.data.message
    if (error.response.status === 409 && error.response.data.result.indexOf('not have permission') > -1) {
      msg = '暂无访问权限'
    }
    if (msg.indexOf('{') > -1 && msg.indexOf('}') > -1) {
      msg = JSON.parse(msg).result || JSON.parse(msg).msg
    }
    Message({
      message: msg,
      type: 'error',
      showClose: true,
      duration: 3000
    })
  } else {
    Message({
      message: '网络异常,请稍后重试',
      type: 'error',
      showClose: true,
      duration: 3000
    })
  }
  return Promise.reject(error)
  // }
})

export default axios

Logo

前往低代码交流专区

更多推荐