JSON Server 可以想像成是一個假後端 ( Fake API )
在React中,只要準備一個 db.json 檔案,就可以立刻把裡面的資料轉換成一個 RESTful API,使用者就可以使用GET、POST、PUT、DELETE 去讀寫資料,就像是模擬前端抓取資料的情境
在專案中建立 data 資料夾 → 再從裡面新建 db.json 的檔案 → 再從 db.json 中撰寫假資料
必須是合法的 JSON 格式
db.json
{
"blogs": [
{
"title": "我們生來就是自由的",
"author": "艾倫",
"id": 1
},
{
"title": "這個世界是很殘酷的,但是也非常美麗",
"author": "米卡莎",
"id": 2
},
{
"title": "什麼都無法捨棄的人,什麼都改變不了",
"author": "阿爾敏",
"id": 3
}
]
}
新增新的終端機 (terninal)
使用:
npx json-server --watch data/db.json --port 8000
此指令的意思 →
用 npx 執行 JSON Server,監聽 data 裡面 db.json 這個檔案,並且在本機的 8000 port 啟動 API 伺服器
之後就會得到 http://localhost:8000/blogs
這個網址,打開之後就會看到資料被寫在後端
API Endpoint 就是 API 提供的一個網址 (URL),前端可以透過它去請求取得或操作資料
假設我們用 json-server --watch db.json --port 8000
:
API 的基礎路徑 = http://localhost:8000
常見的API 的 Endpoint:
http://localhost:8000/blogs
→ 拿到所有部落格文章http://localhost:8000/blogs/1
→ 拿到 id=1 的文章Endpoint | Method | 說明 |
---|---|---|
/blogs | GET | 取得所有文章 |
/blogs/{id} | GET | 取得單一文章 |
/blogs | POST | 新增文章 |
/blogs/{id} | DELETE | 刪除文章 |
下一篇文章會介紹 JSON Server 結合 useEffect 這個 Hook 的功能應用