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

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

xulili's avatar
xulili committed
58
const httpServer = (opts, data, file, timeout) => {
qzhxx's avatar
qzhxx committed
59 60
  //如果是不需要登录就可以访问的接口 需要设置opts.open
  let Public = {} //公共参数
xulili's avatar
xulili committed
61
  let httpDefaultOpts = {
qzhxx's avatar
qzhxx committed
62 63
    method: opts.method,
    url: baseUrl + opts.url,
qzhxx's avatar
qzhxx committed
64
    timeout: timeout ? timeout : 10800000,
xulili's avatar
xulili committed
65 66
    params: Object.assign(Public, data),
    data: data,
qzhxx's avatar
qzhxx committed
67 68 69 70
    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
71 72
  let authToken = "";
  if (opts.authType && opts.authType != "") {
qzhxx's avatar
qzhxx committed
73
    // Authorization
xulili's avatar
xulili committed
74 75 76
    if (opts.authType === "back") {
      authToken = localStorage.getItem('backToken');
    } else if (opts.authType === "front") {
qzhxx's avatar
qzhxx committed
77 78 79 80
      authToken = localStorage.getItem("token") || MyLocalStorage.Cache.get('token');
    }
    httpDefaultOpts.headers["Authorization"]=authToken
  }
xulili's avatar
xulili committed
81
  if (opts.method === 'get') {
qzhxx's avatar
qzhxx committed
82 83
    delete httpDefaultOpts.data
    httpDefaultOpts.params.timestamp_static = new Date().getTime();
xulili's avatar
xulili committed
84
  } else {
qzhxx's avatar
qzhxx committed
85
    delete httpDefaultOpts.params
xulili's avatar
xulili committed
86 87
    if (file) {
      httpDefaultOpts.data = data;
qzhxx's avatar
qzhxx committed
88 89 90
    }
  }

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

xulili's avatar
xulili committed
136
export default httpServer