http.js
2.88 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
98
99
100
101
102
103
104
105
106
107
108
import axios from 'axios';
import { checkStatus, showLoading } from './checkStatus';
const instance = axios.create({ // 创建axios实例,在这里可以设置请求的默认配置
timeout: 60000, // 设置超时时间60s
retry: 3,
retryDelay: 1000
})
// 统一设置post请求头
instance.defaults.headers.post['Content-Type'] = 'application/json'
/** 添加请求拦截器 **/
instance.interceptors.request.use(config => {
config.headers['Authorization'] = localStorage.getItem('token') || '';
showLoading(true);
return config
}, error => {
console.log('请求错误,原因:', error)
showLoading(false);
return Promise.reject(error)
})
/** 添加响应拦截器 **/
instance.interceptors.response.use(response => {
showLoading(false);
const serverCode = response.data.code;
if (serverCode === 200 || response.status === 200) {
if(serverCode !== 200) {
checkStatus(serverCode);
}
if(response.status) {
return Promise.resolve(response);
}
return Promise.resolve(response.data);
} else {
checkStatus(serverCode);
return Promise.reject(response.data.message)
}
}, error => {
showLoading(false);
const errRes = error.response;
if (errRes) {
const { data, config, status, statusText } = errRes;
checkStatus(status);
console.log(`${config.url} 接口请求出错,状态码${status}`);
return Promise.reject(error);
} else {
checkStatus('fail');
console.log('http request fail 请求失败');
return Promise.reject(new Error('请求失败'))
}
// 超时处理
var config = error.config
if (!config || !config.retry) return Promise.reject(error)
// 设置用于跟踪重试次数的变量
config.__retryCount = config.__retryCount || 0
// 检查我们是否已将重试总数最大化
if (config.__retryCount >= config.retry) {
// 错误拒绝
return Promise.reject(error)
}
// 增加重试次数
config.__retryCount += 1
// 创造新的承诺来处理指数退避
var backoff = new Promise(function (resolve) {
setTimeout(function () {
resolve()
}, config.retryDelay || 1)
})
// 返回承诺,其中将撤回axios以重试请求
return backoff.then(function () {
return axios(config)
})
})
export default class HTTP {
axiosPost (options) {
instance({
url: options.url,
method: 'post',
data: JSON.stringify(options.data)
}).then((res) => {
options.success(res.data)
}).catch((err) => {
options.error(err)
})
}
axiosGet (options) {
instance({
url: options.url,
method: 'get',
params: options.data
}).then((res) => {
options.success(res.data);
}).catch((err) => {
options.error(err);
})
}
}