json-server快速建立一个完整的零编码的伪Rest API

json-server


安装

shell 复制代码
npm install json-server

用法

创建 db.jsondb.json5 文件

json 复制代码
{
  "posts": [
    { "id": "1", "title": "a title", "views": 100 },
    { "id": "2", "title": "another title", "views": 200 }
  ],
  "comments": [
    { "id": "1", "text": "a comment about post 1", "postId": "1" },
    { "id": "2", "text": "another comment about post 1", "postId": "1" }
  ],
  "profile": {
    "name": "typicode"
  }
}
查看 db.json5 示例
json5 复制代码
{
  posts: [
    { id: '1', title: 'a title', views: 100 },
    { id: '2', title: 'another title', views: 200 },
  ],
  comments: [
    { id: '1', text: 'a comment about post 1', postId: '1' },
    { id: '2', text: 'another comment about post 1', postId: '1' },
  ],
  profile: {
    name: 'typicode',
  },
}

您可以阅读有关 JSON5 格式的更多信息 here.

将其传递给 JSON Server CLI

shell 复制代码
$ npx json-server db.json

获取 REST API

shell 复制代码
$ curl http://localhost:3000/posts/1
{
  "id": "1",
  "title": "a title",
  "views": 100
}

运行 json-server --help 获取选项列表

路由

根据示例 db.json,您将获得以下路线:

复制代码
GET    /posts
GET    /posts/:id
POST   /posts
PUT    /posts/:id
PATCH  /posts/:id
DELETE /posts/:id

# Same for comments
复制代码
GET   /profile
PUT   /profile
PATCH /profile

参数

条件

  • ==
  • lt<
  • lte<=
  • gt>
  • gte>=
  • ne!=
复制代码
GET /posts?views_gt=9000

范围

  • start
  • end
  • limit
复制代码
GET /posts?_start=10&_end=20
GET /posts?_start=10&_limit=10

分页

  • page
  • per_page (default = 10)
复制代码
GET /posts?_page=1&_per_page=25

排序

  • _sort=f1,f2
复制代码
GET /posts?_sort=id,-views

嵌套和数组字段

  • x.y.z...
  • x.y.z[i]...
复制代码
GET /foo?a.b=bar
GET /foo?x.y_lt=100
GET /foo?arr[0]=bar

嵌入

复制代码
GET /posts?_embed=comments
GET /comments?_embed=post

删除

复制代码
DELETE /posts/1
DELETE /posts/1?_dependent=comments

提供静态文件

如果您创建 ./public 目录,JSON 服务器除了提供 REST API 之外,还会提供其内容。

您也可以使用 -s/--static 选项添加自定义目录。

sh 复制代码
json-server -s ./static
json-server -s ./static -s ./node_modules

与 v0.17 的显著区别

  • id 始终为字符串,如果缺失,系统会为您生成。
  • 使用 _per_page_page 而不是 _limit 进行分页。
  • 使用 Chrome 的 Network tab > throttling 来延迟请求,而不是 --delay CLI 选项。

关于项目

可快速获得一个完整的、零编码的伪 REST API。
Other
Javascript
75,168
7233
1006
2013-11-27
2025-09-15

增长趋势 - stars