http.js 1.23 KB
import axios from 'axios'
import router from './router'

// 请求拦截器
axios.interceptors.request.use(
  config => {
    // 发送请求前
    let hash = location.hash.split('?')[0];
    config.headers['Step-Url'] = location.pathname + hash;
    if (config.params) {
      config.params = _.merge(config.params, { version: 'v.1.1.0 ' })
    } else {
      config.params = {
        version: 'v.1.1.0'
      }
    }
    return config;
  },
  error => {
    // 请求错误处理
    return Promise.reject(error);
  })

// 响应拦截器
axios.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
      case 401:
        if (window.location.hostname === 'localhost') {
          window.location.href = '../login.html';
        } else {
          let h = window.location.origin + '/' + _.split(window.location.pathname, '/', 2)[1] + '/login.html';
          window.location.href = error.response.data.hasOwnProperty('content') ? error.response.data.content : h;
        }
        break;
      case 404:
        router.replace({
          path: '/'
        })
        break;
      }
    }
    return Promise.reject(error.response.data);
  })
export default axios;