--- tags: Note --- # JSON server ### 情境 後端尚未開出 API,但前端開發需要串 API 資料時 ### 介紹 JSON server 可以幫我們建立一個 API server 並能用 RESTful 的方式取資料,只需要準備一個放假資料的 json 檔即可。 ### 開始 1. `npm install -g json-server` 2. `在資料夾底下創建一個檔案放假資料` 假資料生成套件:[faker.js](http://mockjs.com/)、[Mock.js](https://github.com/marak/Faker.js/) ### 範例 > *db.js* ``` { "posts": [ { "id": 1, "title": "json-server", "author": "typicode" } ], "comments": [ { "id": 1, "body": "some comment", "postId": 1 } ], "profile": { "name": "typicode" } } ``` > *posts、comments、profile 皆為路徑名稱。* ``` http://localhost:3000/posts http://localhost:3000/comments http://localhost:3000/profile ``` ### 使用 > *GET* ``` Axios.get(‘http://localhost:3000/posts/') .then(res => { console.log(res.data); }) ``` > *POST* ``` Axios.post('http://localhost:3000/posts/', { id: 2, title: 'hell0', author: 'Debby' }) .then(res => { console.log(res.data); }) ``` 想取特定值或做排序也可以,參考[官方文件](https://github.com/typicode/json-server)。 ### JSONPlaceholder 快速練習如何使用 RESTful API (省去一切瑣碎步驟) ``` https://jsonplaceholder.typicode.com/posts 100 posts https://jsonplaceholder.typicode.com/comments 500 comments https://jsonplaceholder.typicode.com/albums 100 albums https://jsonplaceholder.typicode.com/photos 5000 photos https://jsonplaceholder.typicode.com/todos 200 todos https://jsonplaceholder.typicode.com/users 10 users ``` ### 目前疑惑 - 說只能做假資料,但像我們部落格 API 也是用 json server 做的,看起來也是可以做 CRUD,那為什麼是說只能做假資料?這樣我們 final 是不是其實也可以用 json server 來做出 RESTful API 供前端使用?不用用到 Express?