iT邦幫忙

1

React 學習筆記_18(JSON Server)

  • 分享至 

  • twitterImage
  •  

JSON Server

簡介

使用JSON Server可以快速建立一個虛擬的數據庫,並且支援開發中最常用的 GET、POST、PUT、PATCH、DELETE、OPTIONS 等 request method。

建立JSON-Server

在VS Code中建立一個db.json檔案,將模擬的數據庫數據輸入在上面(下方使用JSON-Server GitHub範例)。

{
    "posts": [
        { 
            "id": 1, 
            "title": "json-server", 
            "author": "typicode" 
        }
    ],
    "comments": [
        { 
          "id": 1, 
          "body": "some comment", 
          "postId": 1 
        }
    ],
    "profile": [ 
        { 
            "name": "typicode" 
        }
    ]
  }

在專案中安裝JSON-Server

npm install -g json-server
yarn add json-server

啟動JSON-Server

Step 1 : 打開pakeage.json
{
  "dependencies": {
    "json-server": "^0.16.1"
  }
}
Step 2 : 加入start與license命令
{
  "dependencies": {
    "json-server": "^0.16.1"
  },
  "scripts":{
    "start": "json-server --watch db.json --port 3004"  //預設3000可以藉由 --port 來改變端口號
  },
  "license": "MIT"
}

json-server --watch db.json預設端口是3000可以藉由 --port來改變自定義的端口號

Step 3 : 使用yarn start啟動JSON-Server

結果 :
https://ithelp.ithome.com.tw/upload/images/20200411/20124767xQPQewAKmq.png

JSON-Server Method

使用Postman 來確認JSON-Server的數據庫狀況。

GET (取得資料)

https://ithelp.ithome.com.tw/upload/images/20200411/20124767ctH2XHoZ33.png

POST (新增資料)

https://ithelp.ithome.com.tw/upload/images/20200411/20124767NmgxytS9ao.png
使用GET來取得變化後的數據 :
https://ithelp.ithome.com.tw/upload/images/20200411/20124767n36bZhGS3o.png

PUT (更新資料)

更改id:2的數據,將"title":Post Try更改為"title":PUT Try
https://ithelp.ithome.com.tw/upload/images/20200411/20124767I3rcvqNtEL.png
使用GET來取得變化後的數據 :
https://ithelp.ithome.com.tw/upload/images/20200411/20124767sLWJgl2IzE.png

DELETE (刪除資料)

將id:2刪除 :
https://ithelp.ithome.com.tw/upload/images/20200411/20124767I4KbefSbZU.png

參考資料 :
GitHub-json-server
使用 JSON Server 快速模擬 Restful API


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言