Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

前端自己來!用 json server 做 RESTful API #23

Open
debbygigigi opened this issue Feb 25, 2019 · 0 comments
Open

前端自己來!用 json server 做 RESTful API #23

debbygigigi opened this issue Feb 25, 2019 · 0 comments

Comments

@debbygigigi
Copy link
Owner

json server

可以做什麼

當我們前端在開發時,會碰到需要透過 API 取資料的時候,這時如果公司的後端還沒開 API 出來就沒辦法做了,或是自己在練習 Project ,沒有後端可以產 API

這時候就是前端當自強了!

json server 就是可以幫我們建立一個 api server,並能用 RESTful 的方式取資料
你需要準備一個放資料的地方,可以是 js 或 json 檔

json server

首先全域安裝 json server

npm install -g json-server

在資料夾底下新建一個放資料的地方,可以是 json 或 js 檔(js 檔必須 export json 格式)
裡面放假資料,假資料可以用 faker.js 或 Mock.js 來產生
以官網的範例,取名為 db.json,內容如下

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

開啟 json server,並且指定使用哪個檔案

json-server db.json     

成功開啟 server 會出現如下圖,還很貼心寫出有哪些 api 可以使用

2019-02-24 4 31 35

在專案裡便可以直接使用這個 API

Axios.get('http://localhost:3000/posts/')
          .then(res => {
            console.log(res.data);
          })

// response: 
[
        //     {
        //        "id":1,
        //        "title":"json-server",
        //        "author":"typicode"
        //     }
        //  ]

也可以使用 POST,可以看到 db.json 也變成了兩筆資料

Axios.post('http://localhost:3000/posts/', {
            id: 2,
            title: 'hell0',
            author: 'Debby'
          })
          .then(res => {
            console.log(res.data);
          })

不只如此,我們取值甚至可以做 filter 跟 sort:

GET\ http://localhost:3000/posts?author=Debby

[
    {
        "id": 2,
        "title": "hell0",
        "author": "Debby"
    }
]

還有很多,可以看文件 https://www.npmjs.com/package/json-server

jsonplaceholder

https://jsonplaceholder.typicode.com/

另一個服務,我覺得很適合作為前端 CRUD 的練習
總共提供6種 api
/posts 100 posts
/comments 500 comments
/albums 100 albums
/photos 5000 photos
/todos 200 todos
/users 10 users

假設今天做了一個 todolist ,就可以用 get https://jsonplaceholder.typicode.com/todos 去獲得資料

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant