json-server 可以完全模拟 REST API 的工具,它可以辅助你的前端项目快速开始。
安装 json-server
npm install -g json-server
添加数据
mock/data.json
- 文件
{
"oauth-token": {},
"mailTemplates": {}
}
添加路由
mock/routes.json
- 文件
格式: "关联路径":"实际路径"
{
"/oauth/token": "/oauth-token",
"/api/v5/mailTemplates": "/mailTemplates"
}
启用服务器
json-server mock/data.json --routes mock/routes.json
使用文档
参考: Github 项目 <链接>
路由
Based on the previous db.json
file, here are all the default routes. You can also add other routes using --routes
.
复数路由
GET /posts
GET /posts/1
POST /posts
PUT /posts/1
PATCH /posts/1
DELETE /posts/1
单数路由
GET /profile
POST /profile
PUT /profile
PATCH /profile
参数
Use .
to access deep properties
GET /posts?title=json-server&author=typicode
GET /posts?id=1&id=2
GET /comments?author.name=typicode
分页
Use _page
and optionally _limit
to paginate returned data.
In the Link
header you’ll get first
, prev
, next
and last
links.
GET /posts?_page=7
GET /posts?_page=7&_limit=20
10 items are returned by default
排序
Add _sort
and _order
(ascending order by default)
GET /posts?_sort=views&_order=asc
GET /posts/1/comments?_sort=votes&_order=asc
For multiple fields, use the following format:
GET /posts?_sort=user,views&_order=desc,asc
切片
Add _start
and _end
or _limit
(an X-Total-Count
header is included in the response)
GET /posts?_start=20&_end=30
GET /posts/1/comments?_start=20&_end=30
GET /posts/1/comments?_start=20&_limit=10
Works exactly as Array.slice (i.e. _start
is inclusive and _end
exclusive)
操作符
Add _gte
or _lte
for getting a range
GET /posts?views_gte=10&views_lte=20
Add _ne
to exclude a value
GET /posts?id_ne=1
Add _like
to filter (RegExp supported)
GET /posts?title_like=server
全文匹配
Add q
GET /posts?q=internet
关联
To include children resources, add _embed
GET /posts?_embed=comments
GET /posts/1?_embed=comments
To include parent resource, add _expand
GET /comments?_expand=post
GET /comments/1?_expand=post
To get or create nested resources (by default one level, add custom routes for more)
GET /posts/1/comments
POST /posts/1/comments
数据库
GET /db
首页
Returns default index file or serves ./public
directory
GET /