# 什么是axios
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中,使用axios这个第三方组件,可以十分便捷的处理ajax数据请求,提高开发效率。
# 前期准备
- 准备好json数据文件。
- 使用json-server启动接口服务器。
- 安装 axios 第三方组件:
yarn add axios
- 引包:
<script src="./node_modules/axios/dist/axios.js"></script>
# 基本请求语法
axios({
method: "请求方式",
url: "请求地址",
//post put patch使用
data: {}, // 参数对象, 在body请求体中传递
//get delete使用
params: {} // 参数对象, 在url地址栏中传递, ?xx=xx
}).then((response) => { 函数体 }) //响应回来的回调函数
.catch((error) => { 函数体 }) //请求或响应失败后的回调函数
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
- 例一:使用GET请求获取list数据
axios({
method: 'get',
url: 'http://localhost:3000/list'
}).then((res) => console.log(res.data))
.catch((err) => console.log(err));
1
2
3
4
5
2
3
4
5
- 例二:执行GET请求,进行数据搜索
//(1) 方法一,使用params属性
axios({
method: 'get',
url: 'http://localhost:3000/list',
// 使用params属性,内部写需要查询的项,比如下:查询id 为 2 的项
params: {
id: 2
}
}).then((res) => console.log(res.data))
.catch((err) => console.log(err));
//(2) 直接使用原GET查询,利用查询参数 ?....
axios({
method: "get",
url: "http://localhost:3000/list?name_like=塞尔达"
}).then((res) => console.log(res.data))
.catch((err) => console.log(err));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- 例三:执行POST请求,进行添加数据
axios({
method: 'post',
url: 'http://localhost:3000/list',
data: {
name: "无主之地2",
price: 78
}
}).then((res) => console.log('添加数据成功'))
.catch((err) => console.log(err));
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 简写语法
简写适用于比较简单的请求。
基本模式:$.ajax({ ... }) type url data success error
- get 和 delete类似
axios.get(url).then(成功的函数)
axios.get(url, {
params: { ... }
}).then(成功的函数)
1
2
3
4
2
3
4
- post 和 put 和 patch 类似
axios.post(url, data).then(成功的函数)
1. get
//例一:获取全部数据请求
axios.get('http://localhost:3000/list').then(res) => console.log(res.data));
1
2
2
2. post
//例二:添加一项数据请求
axios.post(
'http://localhost:3000/list',
{
name: "巫师三",
price: 120
}
).then((res) => console.log('添加数据成功'));
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
3. delete
//例三:删除数据请求
axios.delete('http://localhost:3000/list/3').then((res) => console.log("删除数据成功"));
1
2
2
4. put
//例四:修改数据项全部数据
axios.put(
'http://localhost:3000/list/4',
{
name: "赛博朋克2077",
price: "277"
}
).then((res) => console.log("put修改数据成功"));
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
5. patch
//例五:patch修改部分数据
axios.patch(
'http://localhost:3000/list/2',
{
price: '360'
}
).then((res) => console.log("patch修改数据成功"));
1
2
3
4
5
6
7
2
3
4
5
6
7
执行结果:
