axios使用

学习链接

安装 JSON Server
npm install -g json-server

创建db.json
写入数据

启动服务-所在文件夹下
json-server --watch db.json
可以看见地址了

http://localhost:3000/posts
http://localhost:3000/comments
http://localhost:3000/profile

axios

1
2
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
console.log(axios);

GET-请求
POST-发送-请求体,写入
PUT-更新,指定目录
增删改查

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
<script type="text/javascript">
// 获取按钮
const btns = document.querySelectorAll('button');

// 第一个
btns[0].onclick = function(){
// 发送ajax请求
axios({
// 请求类型
method: 'GET',
// URL
url: 'http://localhost:3000/posts/2'
}).then(response => {
console.log(response);
})
};

btns[1].onclick = function(){
// 发送ajax请求
axios({
// 请求类型
method: 'POST',
// URL
url: 'http://localhost:3000/posts',
// 请求体
data:{
title: 'Post请求',
author: '赞赞'
}
}).then(response => {
console.log(response);
})
};

btns[2].onclick = function(){
// 发送ajax请求
axios({
// 请求类型
method: 'PUT',
// URL
url: 'http://localhost:3000/posts/3',
// 请求体
data:{
title: 'Post请求',
author: '看看'
}
}).then(response => {
console.log(response);
})
};

btns[3].onclick = function(){
// 发送ajax请求
axios({
// 请求类型
method: 'delete',
// URL
url: 'http://localhost:3000/posts/3',
}).then(response => {
console.log(response);
})
};

创建实例-针对不同接口

拦截器-请求拦截,增删改查
响应拦截,查看状态
注意顺序,

请求失败,全部失败
拦截器不返回-找不到数据

取消请求-防止一直发送请求

多个axios并发-顺寻问题
all方法包裹,spread方法处理返回值


mockjs

1
2
3
4
5
6
7
8
9
10
11
12
13
<script src="http://mockjs.com/dist/mock.js"></script>
<script type="text/javascript">
var data = Mock.mock({
// 属性 list 的值是一个数组,其中含有 1 到 10 个元素
'list|1-10': [{
// 属性 id 是一个自增数,起始值为 1,每次增 1
'id|+1': 1
}]
})
// 输出结果
console.log(data)
console.log(JSON.stringify(data, null, 4))
</script>

mock拦截axios请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<script type="text/javascript">
axios.request({
method: 'get',
url: 'https://cdn.liyanhui.com/data.json'
}).then(res => {
console.log(res.data)
})

//Mock拦截
Mock.mock('https://cdn.liyanhui.com/data.json',{
'list|5-10': [
{
'id|+1': 1,
'username': '@cname',
'email': '@email',
'price': '@integer',
'gender': '@boolean'
}
]
})

</script>