json-server 使用

json-server 是用来模拟后端接口返回的数据结构和请求操作的

https://github.com/typicode/json-server

使用全局安装

npm install json-server -g

json-server 会将一个json文件作为数据库来存储数据,对json数据的格式是有要求的,如data.json的内容:

{
  "tb1": [
    {
      "id": 1,
      "title": "标题1",
      "author": "描述信息1"
    },
    {
      "id": 2,
      "title": "标题2",
      "author": "描述信息2"
    }
  ],
  "tb2": [
    {
      "id": 1,
      "body": "some comment",
      "postId": 1
    }
  ],
  "tb3": {
    "name": "typicode"
  }
}

启动服务:

json-server --watch data.json

启动成功后,提示信息如下:

$ json-server --watch data.json

  \{^_^}/ hi!

  Loading data.json
  Done

  Resources
  http://localhost:3000/tb1
  http://localhost:3000/tb2
  http://localhost:3000/tb3

  Home
  http://localhost:3000

  Type s + enter at any time to create a snapshot of the database
  Watching...

得到tb1所有的数据 GET: http://localhost:3000/tb1

根据id得到数据 GET : http://localhost:3000/tb1/2

添加一条数据 POST: http://localhost:3000/tb1

删除一条数据 DELETE: http://localhost:3000/tb1/2

模糊查找 GET : http://localhost:3000/tb1?title_like=标题

根据id修改数据 PUT: http://localhost:3000/tb1/1

注意:json-server 严格遵循 HTTP 请求语义进行数据处理

posted @ 2020-10-18 15:26  makalo  阅读(220)  评论(0编辑  收藏  举报