JSON Server | 模擬 RESTful API取得假資料

目錄
當練習或開發時需要透過 API取得資料,而手邊正沒有符合的 API可以用時,就可以 JSON Sever 這個 JS 套件,幫我們建立一個 API Server,只需要建立一個JSON形式的資料。
JSON Server 安裝步驟
https://github.com/typicode/json-server
-
Install JSON Server
npm install -g json-server -
創建 db.json 並輸入資料
{ "posts": [ { "id": 1, "title": "json-server", "author": "typicode" } ], "comments": [ { "id": 1, "body": "some comment", "postId": 1 } ], "profile": { "name": "typicode" } } -
Start JSON Server
json-server --watch db.json -
訪問 http://localhost:3000/posts/1 就可以得到資料
{ "id": 1, "title": "json-server", "author": "typicode" }
搭配 axios 實作
-
專案資料夾 npm init (使用 npm前要先安裝 node),創建 package.json ,package.json是掌管專案資訊的重要檔案。
-
npm install axios
-
創建一個 main.js,輸入以下代碼
import axios from "axios"; function api() { axios.get('http://localhost:3000/posts').then( (res) => { process.stdout.write(JSON.stringify(res.data)); } ) } api(); -
終端輸入 node main.js ,run 我們的JS檔案,就可以看到抓取到的資料了。
自訂自己的 npm command
-
在 package.json中,在 scripts去定義自己的npm command,這裡命名為 json,去操作 json-server 開啟指令,並設定 port 為8888。
"scripts": { "json": "json-server --watch db.json --port 8888" }, -
設定好後,在 終端機上輸入 npm run json 就可以執行 json-server –watch db.json –port 8888 這項指令。
相關文連結: