分支自 SuZhouGuanHong/TaiYuanTaiZhong

dengjunjie
2024-01-16 5884c9023393061afbe6d3d6e709e53e672ddde8
1
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import axios from 'axios'
// import Vue from 'vue'
// npm install qs
 
axios.defaults.timeout = 50000;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
//axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
 
//'application/json;charset=utf-8';//
if (process.env.NODE_ENV == 'development') {//开发环境
  axios.defaults.baseURL = 'http://localhost:8099/';//8089   //192.168.12.110
}
else if (process.env.NODE_ENV == 'debug') {
  // axios.defaults.baseURL = 'http://127.0.0.1:8990/';//调试环境
}
else if (process.env.NODE_ENV == 'production') {
  axios.defaults.baseURL = 'http://localhost:8099/';//生产环境
}
let ipAddress = axios.defaults.baseURL;
axios.interceptors.request.use((config) => {
  //axios.defaults.headers[_Authorization] = $httpVue.$store.getters.getToken();
 
  //console.log(axios.defaults.headers[_Authorization])
  _showLoading && loading.show(_showLoading);
  if (config.method === 'post') {
    //config.data =qs.stringify(config.data);
    //  console.log('post拦截:' + config.data);
  }
  return config;
}, (error) => {
  _showLoading && loading.close();
  return Promise.reject(error);
});
 
//返回状态判断(添加响应拦截器)
axios.interceptors.response.use((res) => {
  _showLoading && loading.close();
  //对响应数据做些事
  if (res.data.success) {
    return res;
  }
  return Promise.resolve(res);
}, (error) => {
  _showLoading && loading.close();
  let httpMessage = '';
  if (error.response) {
    if (error.response.data && error.response.data.message) {
      httpMessage = error.response.data.message;
    } else if (error.response.status == '404') {
      httpMessage = "没有找到请求的地址";
    }
  }
  else {
    httpMessage = '网络好像出了点问题~'
  }
 
  redirect(error.response || {}, httpMessage);
  return Promise.reject(error.response);
});
 
let $httpVue = null, currentToken = '';
const _Authorization = 'Authorization', _Bearer = 'Bearer ';
function init(vue) {
  $httpVue = vue;
}
let $loading;
let loading = {
  show(obj) {  //可选值为true,string="当前提示的文本"
    let text = '正在处理中.....';
    if (typeof obj == 'string') {
      text = obj;
    }
    $loading && $loading.close();
    $loading = $httpVue.$loading({
      lock: true,
      target: '#loading-container',
      customClass: "el-loading",
      text: text,
      spinner: 'el-icon-loading',
      background: 'rgba(58, 61, 63, 0.32)'
    });
  },
  close() {
    $loading.close();
  }
}
function getToken() {
  if (currentToken) {
    return _Bearer + currentToken;
  }
  return $httpVue.$store.getters.getToken();
}
let _showLoading;
//_showLoading=true异步请求时会显示遮罩层,_showLoading=字符串,异步请求时遮罩层显示当前字符串
function post(url, params, showLoading) {
  _showLoading = showLoading;
  axios.defaults.headers[_Authorization] = getToken();
  return new Promise((resolve, reject) => {
    //  axios.post(url, qs.stringify(params))   //
    axios.post(url, params)
      .then(response => {
        if (response.status == 202) {
          getNewToken(() => { post(url, params, _showLoading); });
          return;
        }
        resolve(response.data);
      }, err => {
      
        if (err.status == 202) {
          getNewToken(() => { post(url, params, _showLoading); });
          return;
        }
        reject(err.data && err.data.message ? err.data.message : '网络好像出了点问题~~');
      })
      .catch((error) => {
        reject(error)
      })
  })
}
 
//_showLoading=true异步请求时会显示遮罩层,_showLoading=字符串,异步请求时遮罩层显示当前字符串
function get(url, param, showLoading) {
  _showLoading = showLoading;
  axios.defaults.headers[_Authorization] = getToken();
  return new Promise((resolve, reject) => {
    axios.get(url, { params: param })
      .then(response => {
        if (response.status == 202) {
          getNewToken(() => { get(url, param, _showLoading); });
          return;
        }
        resolve(response.data)
      }, err => {
        if (err.status == 202) {
          getNewToken(() => { get(url, param, _showLoading); });
          return;
        }
        redirect(response.data);
        reject(err)
      })
      .catch((error) => {
        reject(error)
      })
  })
}
 
 
 
 
function createXHR() {
  if (XMLHttpRequest) {
    return new XMLHttpRequest();
  }
  if (ActiveXObject) {
    if (typeof arguments.callee.activeXString != "string") {
      var versions = [
        "MSXML2.XMLHttp.6.0",
        "MSXML2.XMLHttp",
        "MSXML2.XMLHttp.3.0"
      ];
      for (var i = 0; i < versions.length; i++) {
        try {
          new ActiveXObject(versions[i]);
          arguments.callee.activeXString = versions[i];
          break;
        } catch (e) {
          console.log("no");
        }
      }
    }
    return new ActiveXObject(arguments.callee.activeXString);
  }
}
 
function redirect(responseText, message) {
  try {
    let responseData = typeof responseText == 'string' ? JSON.parse(responseText) : responseText;
    //  $httpVue.$message.error(responseData.message || '~服务器好像出了点问题...')
    if ((responseData.hasOwnProperty('code') && responseData.code == 401)
      || (responseData.data && responseData.data.code == 401)) {
      toLogin();
    } else {
      $httpVue.$message.error(message);
    }
  } catch (error) {
    console.log(error);
    $httpVue.$message.error(responseText)
  }
}
function toLogin() {
  currentToken = "";
  $httpVue.$router.push({ path: '/login', params: { r: Math.random() } });
}
//当前token快要过期时,用现有的token换成一个新的token
function getNewToken(callBack) {
  ajax({
    url: "/api/User/replaceToken",
    param: {},
    json: true,
    success: function (x) {
      if (x.status) {
        let userInfo = $httpVue.$store.getters.getUserInfo();
        userInfo.token = x.data;
        currentToken = x.data;
        $httpVue.$store.commit('setUserInfo', userInfo);
        callBack();
      } else {
        console.log(x.message);
        toLogin();
      }
    },
    errror: function (ex) {
      console.log(ex);
      toLogin();
    },
    type: "post",
    async: false
  });
 
 
}
 
function ajax(param) {
  let httpParam =
    Object.assign({
      url: '', headers: {},
      param: {}, json: true,
      success: function () { },
      errror: function () { },
      type: 'post', async: true
    }, param);
 
  httpParam.url = axios.defaults.baseURL + httpParam.url.replace(/\/?/, '');
  httpParam.headers[_Authorization] = getToken();
  var xhr = createXHR();
  // console.log(xhr.readyState);
  xhr.onreadystatechange = function () {
    if (xhr.status == 403 || xhr.status == 401) {
      redirect(xhr.responseText);
      return;
    }
    if (xhr.status == 202) {
      getNewToken(() => {
        ajax(param);
      });
      return;
    }
    if (xhr.readyState == 4 && xhr.status == 200) {
      httpParam.success(httpParam.json ? JSON.parse(xhr.responseText) : xhr.responseText);
      return;
    }
    if (xhr.status != 0 && xhr.readyState != 1) {
      httpParam.errror(xhr);
    }
  };
  //初始化请求
  xhr.open(
    httpParam.type,
    httpParam.url,
    httpParam.async
  );
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  for (const key in httpParam.headers) {
    xhr.setRequestHeader(key, httpParam.headers[key]);
  }
  let dataStr = '';
  for (const key in httpParam.param) {
    dataStr += key + "=" + httpParam.param[key];
  }
  try {
    xhr.send(dataStr);
  } catch (error) {
    toLogin();
    //  console.log(error)
  }
}
 
ajax.post = function (url, param, success, errror) {
  ajax({ url: url, param: param, success: success, error: errror, type: 'post' })
}
ajax.get = function (url, param, success, errror) {
  ajax({ url: url, param: param, success: success, error: errror, type: 'post' })
}
export default { post, get, ajax, init, ipAddress }