blog
blog copied to clipboard
前端模拟api数据的两种方式
json-server
1.全局安装
$ npm install -g json-server
2.创建db.json
文件
{
"records": [
{
"id": "1",
"date": "2018-05-17",
"title": "title 1",
"amount": 88
},
{
"id": "2",
"date": "2018-05-18",
"title": "title 2",
"amount": 23
},
{
"id": "3",
"date": "2018-05-19",
"title": "title 3",
"amount": 3
},
{
"id": "4",
"date": "2018-05-20",
"title": "title 4",
"amount": 8
},
{
"id": "5",
"date": "2018-05-21",
"title": "title 5",
"amount": 88
}
]
}
3.开启服务并在指定端口更新
在db.json
目录打开
json-server --watch db.json --port 3006
4.get 获取数据
根据id
获取单个详情数据
或者
http://localhost:3000/records?id=1
过滤功能:
使用
.
更可以访问深层属性,如:GET /posts?id=1&id=2
GET /comments?author.name=typicode
分页展示功能:
5.put 更新数据
准备更新
发送请求,send
注意:这里是全量更新替换
6.post 添加数据
准备添加
发送请求,send
7.delete 删除数据
准备删除
发送delete
请求,send
mockapi
使用方法与上 json-server
相似,这里不再赘述...
useful links
- http://www.mockapi.io/
- https://github.com/typicode/json-server
- https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch
- https://github.com/github/fetch
- https://github.com/matthew-andrews/isomorphic-fetch
- https://github.com/mdn/fetch-examples