json-server 可以完全模拟 REST API 的工具,它可以辅助你的前端项目快速开始。

安装 json-server

  1. npm install -g json-server

添加数据

mock/data.json - 文件

  1. {
  2. "oauth-token": {},
  3. "mailTemplates": {}
  4. }

添加路由

mock/routes.json - 文件
格式: "关联路径":"实际路径"

  1. {
  2. "/oauth/token": "/oauth-token",
  3. "/api/v5/mailTemplates": "/mailTemplates"
  4. }

启用服务器

  1. 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.

复数路由

  1. GET /posts
  2. GET /posts/1
  3. POST /posts
  4. PUT /posts/1
  5. PATCH /posts/1
  6. DELETE /posts/1

单数路由

  1. GET /profile
  2. POST /profile
  3. PUT /profile
  4. PATCH /profile

参数

Use . to access deep properties

  1. GET /posts?title=json-server&author=typicode
  2. GET /posts?id=1&id=2
  3. 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.

  1. GET /posts?_page=7
  2. GET /posts?_page=7&_limit=20

10 items are returned by default

排序

Add _sort and _order (ascending order by default)

  1. GET /posts?_sort=views&_order=asc
  2. GET /posts/1/comments?_sort=votes&_order=asc

For multiple fields, use the following format:

  1. GET /posts?_sort=user,views&_order=desc,asc

切片

Add _start and _end or _limit (an X-Total-Count header is included in the response)

  1. GET /posts?_start=20&_end=30
  2. GET /posts/1/comments?_start=20&_end=30
  3. 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

  1. GET /posts?views_gte=10&views_lte=20

Add _ne to exclude a value

  1. GET /posts?id_ne=1

Add _like to filter (RegExp supported)

  1. GET /posts?title_like=server

全文匹配

Add q

  1. GET /posts?q=internet

关联

To include children resources, add _embed

  1. GET /posts?_embed=comments
  2. GET /posts/1?_embed=comments

To include parent resource, add _expand

  1. GET /comments?_expand=post
  2. GET /comments/1?_expand=post

To get or create nested resources (by default one level, add custom routes for more)

  1. GET /posts/1/comments
  2. POST /posts/1/comments

数据库

  1. GET /db

首页

Returns default index file or serves ./public directory

  1. GET /