# 9.Json-server
# 安装与使用
npm install -g json-server
1
创建一个db.json
的文件:
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
然后,使用:
json-server --watch db.json
1
就可以在http://localhost:3000/posts/1
获取对应的数据了:
{ "id": 1, "title": "json-server", "author": "typicode" }
1
所有数据的POST, PUT, PATCH,DELETE请求都会得到响应。
# 动态数据
例如启动json-server的命令:json-server --watch app.js
是把一个js文件返回的数据托管成web服务。
app.js
配合mockjs (opens new window)库可以很方便的进行生成模拟数据。
const Mock = require("mockjs");
const Random = Mock.Random;
const key = "lists|6-10";
// const result = Random.capitalize("hello");
// 自定义占位符
Random.extend({
hobby: function() {
var arr = ["swim", "run", "play computer game", "ride"];
return this.pick(arr);
}
});
const result = Mock.mock({
[key]: [
{
"id|+1": 1,
name: "@cname",
email: "@email",
picture: "@image('120x120', '#dcdcdc')",
remark: "@title",
address: "@city(true)",
"gender|0-1": 0,
hobby: "@hobby"
}
]
});
module.exports = () => result;
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
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
当json-server启动之后,mock数据就不会变化了,可以使用nodemon配合着使用,以达到接口随机数据变化的目的。
# 自定义路由
当然你可以自定义路由:
$ json-server --routes route.json --watch db.json
1
route.json
文件
{
"/api/*": "/$1",
"/:resource/:id/show": "/:resource/:id",
"/posts/:category": "/posts?category=:category",
"/articles\\?id=:id": "/posts/:id"
}
1
2
3
4
5
6
2
3
4
5
6
对应的请求会进行转发:
/api/posts # → /posts
/api/posts/1 # → /posts/1
/posts/1/show # → /posts/1
/posts/javascript # → /posts?category=javascript
/articles?id=1 # → /posts/1
1
2
3
4
5
2
3
4
5
# 过滤查询
查询数据,可以额外提供
GET /posts?title=json-server&author=typicode
GET /posts?id=1&id=2
# 可以用 . 访问更深层的属性。
GET /comments?author.name=typicode
1
2
3
4
5
2
3
4
5
还可以使用一些判断条件作为过滤查询的辅助。
GET /posts?views_gte=10&views_lte=20
1
可以用的拼接条件为:
_gte
: 大于等于_lte
: 小于等于_ne
: 不等于_like
: 包含
GET /posts?id_ne=1
GET /posts?id_lte=100
GET /posts?title_like=server
1
2
3
2
3
分页查询
默认后台处理分页参数为: _page
第几页, _limit
一页多少条。
GET /posts?_page=7
GET /posts?_page=7&_limit=20
1
2
2
默认一页10条。
后台会返回总条数,总条数的数据在响应头:X-Total-Count
中。
排序
- 参数:
_sort
设定排序的字段 - 参数:
_order
设定排序的方式(默认升序)
GET /posts?_sort=views&_order=asc
GET /posts/1/comments?_sort=votes&_order=asc
1
2
2
支持多个字段排序:
GET /posts?_sort=user,views&_order=desc,asc
1