Blame view

report-ui/src/utils/request.js 3.48 KB
王涛 authored
1
import axios from 'axios'
wangtao authored
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
import {Message, MessageBox} from 'element-ui'
import {getToken} from '@/utils/auth'


const getParams = () => {
  let map = {};
  let query = window.location.search.substring(1);
  if (query == '') {
    query = document.location.href
    let args = query.split('?');
    let arr = [];
    if (args && args.length > 1) {
      arr = args[1].split('&')
    }
    for (let i = 0; i < arr.length; i++) {
      let pair = arr[i].split("=");
      map[pair[0]] = pair[1];
    }
    return map;
  }
  let vars = query.split("&");
  for (let i = 0; i < vars.length; i++) {
    let pair = vars[i].split("=");
    map[pair[0]] = pair[1];
  }
  return map;
}
wangtao authored
29 30 31 32 33 34 35 36 37 38 39 40 41 42
const getVal = (key) => {
  if(key){
    let val = getParams()[key];
    if(!val){
      val = localStorage.getItem(key);
    }

    if(val){
      localStorage.setItem(key,val);
    }
    return val;
  }
  return '';
}
wangtao authored
43
王涛 authored
44 45
// 创建axios实例
const service = axios.create({
wangtao authored
46
  baseURL: process.env.BASE_API,// api 的 base_url
王涛 authored
47
  timeout: 120000 // 请求超时时间
王涛 authored
48 49 50 51 52 53
})

// request拦截器
service.interceptors.request.use(
  config => {
    config.headers['Authorization'] = (getToken() == null || getToken() == undefined) ? '' : getToken()
wangtao authored
54 55

    // 平台token
wangtao authored
56
    let mjToken = getVal('AuthVal');
wangtao authored
57
    if (mjToken) {
zhangtianqi authored
58
      let hash = btoa(encodeURIComponent(window.location.hash));
wangtao authored
59
      let url = config.url;
wangtao authored
60 61
      let userId = getVal('userId');
      let userName = getVal('nickName');
wangtao authored
62 63

      switch (config.method) {
wangtao authored
64
        case 'POST':
wangtao authored
65 66 67
        case 'post':
          config.headers.AuthorizationMj = "BearerMj " + mjToken + ""
          config.headers.MjUserId = userId;
wangtao authored
68
          config.headers.MjUserName = encodeURIComponent(userName);
wangtao authored
69 70 71 72 73 74 75 76 77 78 79 80 81 82
          config.headers.MjHash = hash;
          break;
        default:
          var access_token  = `accessToken=${mjToken}&MjUserId=${userId}&MjUserName=${userName}&MjHash=${hash}`;
          if (url.indexOf('?') === -1) {
            url += '?' + access_token;
          } else {
            url += '&' + access_token;
          }
          config.url = url;
      }
    }

王涛 authored
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
    return config
  },
  error => {
    // Do something with request error
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    /**
     * code为非20000是抛错 可结合自己业务进行修改
     */
    const res = response.data
    // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
    if (res.code == '50008' || res.code == '50012' || res.code == '50014') {
      MessageBox.confirm(
        '你已被登出,可以取消继续留在该页面,或者重新登录',
        '重新登录',
        {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        sessionStorage.clear()
        localStorage.clear()
        window.location.href = "/";
      })
wangtao authored
113
    } else if (res.code !== '200') {
王涛 authored
114 115 116 117 118 119 120 121 122 123 124
      Message({
        message: res.message,
        type: 'error',
        duration: 5 * 1000
      })
      return response.data
    } else {
      return response.data
    }
  },
  error => {
125
    //start lsq 超时用console输出信息 2022-03-14
wangtao authored
126 127 128
    if (error.code == 'ECONNABORTED' && error.message.indexOf('timeout') != -1) {
      console.log(error.message)
    } else {
129 130 131 132 133 134 135
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
    }
    //end lsq 2022-03-14
王涛 authored
136 137 138 139 140
    return Promise.reject(error)
  }
)

export default service