json-server的使用(接口数据mock好帮手)

简介

json-server: 接口数据mock好帮手

新建文件<db.json>, 内容如下:

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
{
"posts": [
{
"id": 1,
"title": "json-server",
"author": "typicode"
}
],
"comments": [
{
"id": 1,
"body": "some comment",
"postId": 1
}
],
"profile": {
"name": "typicode"
},
"users": [
{
"id": 1,
"name": "rexhang",
"guid": "ee7a6768-bb2c-423c-ac06-5c7905c035b5",
"time": "Wed, 14 Dec 1970 13:20:02 GMT"
}
]
}
  1. 安装&启动

    1. npm install -g json-server

    2. 默认启动在localhost:3000端口,参数: 可以监听文件变化 –watch, 可以指定端口号 –port, 可以指定host –host

    3. json-server --watch db.json --port 8111 --host 127.0.0.1

    4. 然后会以JSON成员为键名,生成若干个请求地址,http://127.0.0.1:8111/JSON_KEY

  2. 请求方法(实现CURD) with REST Client(Ext) -> 直达官网

    1. Create

      1
      2
      3
      4
      5
      6
      7
      8
      9
      ###
      POST http://127.0.0.1:8111/users
      content-type: application/json

      {
      "name": "rexhang",
      "guid": "{{$guid}}",
      "time": "{{$datetime rfc1123|iso8601}}"
      }
    2. Update

      1
      2
      3
      4
      5
      6
      7
      ###
      PATCH http://127.0.0.1:8111/users/1
      content-type: application/json

      {
      "name": "rexhang"
      }
    3. Read

      1
      2
      ###
      GET http://127.0.0.1:8111/profile
      1
      2
      3
      4
      ###
      GET http://127.0.0.1:8111/users
      ?id=1
      &name=rexhang
    4. Delete

      1
      2
      ###
      DELETE http://127.0.0.1:8111/users/1