json-server 可以用于模拟请求 ----Restful风格
查询 get params:{}
增加 post data:{}
删除 delete
修改 put /patch data:{}
使用步骤
1-全局安装 npm i json-server -g / yarn global add json-server 相当于安装了一个命令行工具
2-准备json文件
{
"list": [
{
"name": "斑老师",
"flag": true,
"id": 6
},
{
"name": "猫咪老师",
"flag": true,
"id": 8
}
]
}
3-在当前json文件下运行 json-server data.json 开启本地服务
开启服务
4-看到上图表示服务开启成功 http://localhost:3000/list
增删改查----axios
查询以axios为例 请求方式为get
1-查询全部数据 并且按照id进行排序 排序方式为降序排序
axios({
method: "get",
url: "http://localhost:3000/list?_sort=id&_order=desc"
}).then(res => {
this.list = res.data;
}).catch(err => {
console.log(err);
})
2-查询指定id的数据 http://localhost:3000/list/6
axios({
method: "get",
url: "http://localhost:3000/list/6"
}).then(res => {
this.list = res.data;
}).catch(err => {
console.log(err);
})
3-增加数据post
axios({
method: "post",
url: "http://localhost:3000/list",
data: {
name: todoName,
flag: false
}
}).then(res => {
this.getData()
}).catch(err => {
console.log(err);
})
4-删除指定id的数据
axios({
method: "delete",
url: `http://localhost:3000/list/${id}`,
}).then(res => {
this.getData();
}).catch(err => {
console.log(err);
})
url: `http://localhost:3000/list/${id}`, 这个位置用到了es6的模板字符串
5-修改数据
屏幕快照 2019-07-01 17.42.19.png
axios({
method: "patch",
url: `http://localhost:3000/list/${id}`,
data: {
flag
}
}).then(res => {
this.getData();
}).catch(err => {
console.log(err);
})
补充点:put和patch的区别
put和patch都可以进行修改操作
区别
put 方式如果没有将所有属性都写完整 没写的属性会丢失
patch方式没修改的属性不写默认为之前的值
举例:{id:1,name:"zs",age:18}
修改age=20
put:{id:1,age:20}
patch:{id:1,name:"zs",age:20}