axios

基本使用

增删改查,get查,post增,put改,delete查

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
<body>
<button id="1">点我</button>
<button id="2">点我2</button>
<button id="3">点我3</button>
<button id="5">点我5</button>
<script>
var btn = document.getElementById('1')
var btn2 = document.getElementById('2')
var btn3 = document.getElementById('3')
var btn5 = document.getElementById('5')
btn.onclick=function(){
axios({
method:'GET',
url: 'http://localhost:3000/posts',
}).then(response=>{
console.log(response)
});
}
btn2.onclick=function(){
axios({
method:'POST',
url: 'http://localhost:3000/posts',
data:{
title: "hello world",
author: "chenhao"
}
}).then(value=>{
console.log(value)
},reason=>{
console.log(reason)
});
}
btn3.onclick=function(){
axios({
method:'delete',
url: 'http://localhost:3000/posts/3',

}).then(value=>{
console.log(value)
},reason=>{
console.log(reason)
});
}
btn5.onclick=function(){
axios({
method:'PUT',
url: 'http://localhost:3000/posts/2',
data:{
title: "hello world",
author: "libai"
}
}).then(value=>{
console.log(value)
},reason=>{
console.log(reason)
});
}
</script>
</body>

image-20211212222406097

默认配置

1
2
axios.defaults.method='POST'
axios.defaults.baseURL='http://localhost:3000'

拦截器

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
 		//增加一个请求拦截器
axios.interceptors.request.use(function (config) {
// Do something before request is sent
console.log("请求拦截器成功")
return config;
}, function (error) {
// Do something with request error
console.log("请求拦截器失败")
return Promise.reject(error);
});

//增加一个响应拦截器
axios.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
console.log("响应拦截器成功")
return response;
}, function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
console.log("响应拦截器成功")
// Do something with response error
return Promise.reject(error);
});
axios({
method:'GET',
url: 'http://localhost:3000/posts'

})