forked from ronffy/axios-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
120 lines (99 loc) · 2.46 KB
/
index.js
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
import axios from "axios";
import _ from "lodash";
const write = function (name, value, expires) {
let cookie = [];
cookie.push(name + '=' + encodeURIComponent(value));
if (expires) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
document.cookie = cookie.join('; ');
};
write('whr', '333')
console.log('默认配置:', axios.defaults);
// 超时设置
axios.defaults.timeout = 10000;
// 设置通用头部
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
// 跨域携带cookie
axios.defaults.withCredentials = true;
// 拦截请求
axios.interceptors.request.use(config => {
console.log(1)
config.headers['Authorization'] = 'whr2'
return config
}, error => {
// 提问:什么时候会提交请求失败?
console.log(error);
})
axios.interceptors.request.use(config => new Promise(res => {
setTimeout(() => {
console.log(2);
config.headers['Authorization'] = 'whr3'
res(config);
}, 1000);
}), error => error)
// 拦截响应
axios.interceptors.response.use(response => {
console.log(4, 's');
response.code = 1;
return response
}, error => {
console.log(4, 'e');
const { response, config = {} } = error;
const { url } = config;
let status, message;
if (response && _.isPlainObject(response)) {
const { data, statusText } = response;
status = response.status;
message = data.message || statusText;
} else {
status = 600
message = error.message || 'Network Error'
}
return Promise.reject({
code: 0,
url,
message,
status,
})
})
// axios.interceptors.response.use(response => {
// console.log(3, 's');
// response.code = 1;
// return response
// }, error => {
// console.log(3, 'e');
// })
console.log('拦截器:', axios.interceptors);
let d = +new Date();
axios.get('http://jsonplaceholder.typicode.com/users', {
// axios.get('http://localhost:3000', {
params: {
b: 2
},
headers: {
'Authorization': 'whr1',
},
cancelToken: new axios.CancelToken(cancel => {
let s = setInterval(() => {
if (+new Date() - d > 20000) {
clearInterval(s);
console.log('cancel');
cancel('就是想取消了');
}
}, 100);
}),
// transformResponse: [
// ...axios.defaults.transformResponse,
// (data) => {
// // debugger
// return data.toString();
// }
// ]
})
.then(data => {
console.log('请求成功的数据:', data);
})
.catch(err => {
console.log('请求失败:', err);
})