1. 程式人生 > 實用技巧 >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 請求語義進行資料處理