httpServer.js 4.29 KB
Newer Older
qzhxx's avatar
qzhxx committed
1 2 3 4 5
/**
 * Created by supervisor on 2017/11/3.
 */
import axios from 'axios'
import store from '../store'
xulili's avatar
xulili committed
6
import { Message, MessageBox, Loading } from 'element-ui';
qzhxx's avatar
qzhxx committed
7
import router from '../router'
xulili's avatar
xulili committed
8
import { baseUrl } from './env'
qzhxx's avatar
qzhxx committed
9
import MyLocalStorage from './myLocalStorage'
xulili's avatar
xulili committed
10
import { loginOut } from './loginOut'
qzhxx's avatar
qzhxx committed
11 12

//axios 拦截器 请求时的拦截
xulili's avatar
xulili committed
13
axios.interceptors.request.use(config => {
qzhxx's avatar
qzhxx committed
14
  // 发送请求之前做一些处理
xulili's avatar
xulili committed
15
  store.commit('UPDATE_LOADING', true) //显示loading
qzhxx's avatar
qzhxx committed
16 17 18 19
  // config.headers = {
  //   'Content-Type': 'application/json'
  // };
  return config
xulili's avatar
xulili committed
20
}, error => {
qzhxx's avatar
qzhxx committed
21 22 23 24
  // 当请求异常时做一些处理
  return new Promise.reject(error)
})
// 响应时拦截
xulili's avatar
xulili committed
25
axios.interceptors.response.use(response => {
qzhxx's avatar
qzhxx committed
26 27
  // 返回响应时做一些处理
  return response
xulili's avatar
xulili committed
28
}, error => {
qzhxx's avatar
qzhxx committed
29 30 31 32
  // 当响应异常时做一些处理
  return Promise.resolve(error.response)
})
function errorState(status, data) {
xulili's avatar
xulili committed
33 34 35
  store.commit('UPDATE_LOADING', false)
  if (data.resultCode == '1109') {
    loginOut()
qzhxx's avatar
qzhxx committed
36 37 38
    MessageBox.alert('您的登录过期,请重新登录!', '提示', {
      confirmButtonText: '确定',
      callback: () => {
xulili's avatar
xulili committed
39
        router.push({ path: '/', query: { redirect: router.history.current.fullPath } })
qzhxx's avatar
qzhxx committed
40 41
      }
    });
xulili's avatar
xulili committed
42
  } else if (status === 401) {
qzhxx's avatar
qzhxx committed
43 44 45 46 47 48
    MessageBox.alert('您的用户权限已被禁用,请联系管理员!', '提示', {
      confirmButtonText: '确定',
      callback: () => {
        //这个时候点击确定后清除用户信息
        localStorage.removeItem('backToken')
        localStorage.removeItem('userId')
xulili's avatar
xulili committed
49 50
        router.push({ path: '/', query: { redirect: router.history.current.fullPath } })
        store.commit('isAdminInfo', false);
qzhxx's avatar
qzhxx committed
51 52 53 54
      }
    });
  } else if (status === 500 && data.message.indexOf("not have permission") !== -1) {
    Message.error("抱歉,你无权访问该页面!")
xulili's avatar
xulili committed
55
  } else if (!data) {
qzhxx's avatar
qzhxx committed
56 57 58 59
    Message.error("网络出小差咯~")
  }
}
function successState(res) {
xulili's avatar
xulili committed
60
  store.commit('UPDATE_LOADING', false) //隐藏loading
qzhxx's avatar
qzhxx committed
61 62
}

xulili's avatar
xulili committed
63
const httpServer = (opts, data, file, timeout) => {
qzhxx's avatar
qzhxx committed
64 65
  //如果是不需要登录就可以访问的接口 需要设置opts.open
  let Public = {} //公共参数
xulili's avatar
xulili committed
66
  let httpDefaultOpts = {
qzhxx's avatar
qzhxx committed
67 68
    method: opts.method,
    url: baseUrl + opts.url,
xulili's avatar
xulili committed
69 70 71
    timeout: timeout ? timeout : 20000,
    params: Object.assign(Public, data),
    data: data,
qzhxx's avatar
qzhxx committed
72 73 74 75
    headers: opts.headers || {},
  };
  httpDefaultOpts.headers["Access-control-Allow-Origin"] = "*";
  httpDefaultOpts.headers["Access-Control-Allow-Headers"] = "content-type,x-requested-with";
xulili's avatar
xulili committed
76 77
  let authToken = "";
  if (opts.authType && opts.authType != "") {
qzhxx's avatar
qzhxx committed
78
    // Authorization
xulili's avatar
xulili committed
79 80 81
    if (opts.authType === "back") {
      authToken = localStorage.getItem('backToken');
    } else if (opts.authType === "front") {
qzhxx's avatar
qzhxx committed
82 83 84 85
      authToken = localStorage.getItem("token") || MyLocalStorage.Cache.get('token');
    }
    httpDefaultOpts.headers["Authorization"]=authToken
  }
xulili's avatar
xulili committed
86
  if (opts.method === 'get') {
qzhxx's avatar
qzhxx committed
87 88
    delete httpDefaultOpts.data
    httpDefaultOpts.params.timestamp_static = new Date().getTime();
xulili's avatar
xulili committed
89
  } else {
qzhxx's avatar
qzhxx committed
90
    delete httpDefaultOpts.params
xulili's avatar
xulili committed
91 92
    if (file) {
      httpDefaultOpts.data = data;
qzhxx's avatar
qzhxx committed
93 94 95
    }
  }

xulili's avatar
xulili committed
96
  let promise = new Promise(function (resolve, reject) {
qzhxx's avatar
qzhxx committed
97 98 99 100 101 102 103
    let loadingInstance = Loading.service({
      fullscreen: true,
      lock: true,
      background: 'rgba(0,0,0,.5)',
      text: 'Loading',
      spinner: 'el-icon-loading'
    })
xulili's avatar
xulili committed
104
    let markIndex = setTimeout(function () {
qzhxx's avatar
qzhxx committed
105
      loadingInstance.close();
xulili's avatar
xulili committed
106 107
    }, 10000)
    axios(httpDefaultOpts).then((res) => {
qzhxx's avatar
qzhxx committed
108 109
      loadingInstance.close();
      clearTimeout(markIndex)
xulili's avatar
xulili committed
110 111
      if (res.data.resultCode == '1109' && localStorage.getItem('backToken')) {
        //清除用户信息
qzhxx's avatar
qzhxx committed
112
        errorState(res.status, res.data)
xulili's avatar
xulili committed
113 114 115
      } else {
        successState(res)
        resolve(res)
qzhxx's avatar
qzhxx committed
116
      }
xulili's avatar
xulili committed
117
    }).catch((response) => {
qzhxx's avatar
qzhxx committed
118 119 120
      loadingInstance.close();
      clearTimeout(markIndex)
      console.log("catch")
xulili's avatar
xulili committed
121
      if (response && response.response && response.response.status && response.response.data) {
qzhxx's avatar
qzhxx committed
122 123 124
        errorState(response.response.status, response.response.data)
      }
      reject(response)
xulili's avatar
xulili committed
125 126
      if (response.response.data) {
        if (response.response.data.message) {
qzhxx's avatar
qzhxx committed
127
          Message.error(response.response.data.message)
xulili's avatar
xulili committed
128
        } else {
qzhxx's avatar
qzhxx committed
129 130 131 132 133 134 135 136
          Message.error("操作失败!")
        }
      }
    })
  })
  return promise
}

xulili's avatar
xulili committed
137
export default httpServer