http.js
2.38 KB
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
/**
* axios 全局配置
*/
import axios from 'axios'
import vue from 'vue'
import router from '../router'
const service = axios.create({
timeout: 2000000 //设置请求超时时间
})
import { Message, Loading } from 'element-ui';
let loading //定义loading变量
function startLoading() { //使用Element loading-start 方法
loading = Loading.service({
lock: true,
text: '加载中……',
background: 'rgba(0, 0, 0, 0.7)'
})
}
function endLoading() { //使用Element loading-close 方法
loading.close()
}
//那么 showFullScreenLoading() tryHideFullScreenLoading() 要干的事儿就是将同一时刻的请求合并。
//声明一个变量 needLoadingRequestCount,每次调用showFullScreenLoading方法 needLoadingRequestCount + 1。
//调用tryHideFullScreenLoading()方法,needLoadingRequestCount - 1。needLoadingRequestCount为 0 时,结束 loading。
let needLoadingRequestCount = 0
export function showFullScreenLoading() {
if (needLoadingRequestCount === 0) {
startLoading()
}
needLoadingRequestCount++
}
export function tryHideFullScreenLoading() {
if (needLoadingRequestCount <= 0) return
needLoadingRequestCount--
if (needLoadingRequestCount === 0) {
endLoading()
}
}
/**@param
* 请求前的拦截器
*/
service.interceptors.request.use(function (config) {
const token = localStorage.getItem('atoken');
//截取API添加时间戳防止请求缓存
if (config.method == "get") {
config.params = {
_t: Date.parse(new Date()) / 1000,
...config.params
};
}
if (config.url.indexOf('codes/countries') < 1) {
if (config.url.indexOf('cates') < 1) {
if (token) {
// config.headers.authorization = '4db5183a-721b-4eee-b623-1d143890e813';
config.headers.authorization = token;
//showFullScreenLoading();
} else {
router.push('/');
}
}
}
return config
}, function (err) {
//tryHideFullScreenLoading();
});
/**
* @param
* 响应前的拦截器
*/
service.interceptors.response.use(function (res) {
//tryHideFullScreenLoading();
if (res.data) {
if (res.data.ecode === 401) {
Message({
type: 'error',
message: res.data.enote
})
// router.push('/');
}
}
return res;
}, function (err) {
//tryHideFullScreenLoading();
return Promise.reject(err);
})
export default service