1. 程式人生 > 其它 >json-server和faker.js模擬REST API

json-server和faker.js模擬REST API

今天發現了一個神器——json-server!在他的幫助下可以在很短的時間內搭建一個Rest API, 然後就可以讓前端在不依賴後端的情況下進行開發啦!

關於什麼是RESTful API:
《RESTful API 設計指南》—— 阮一峰
http://www.ruanyifeng.com/blo...

JSON-Server

簡單來說,JSON-Server是一個Node模組,執行Express伺服器,你可以指定一個json檔案作為api的資料來源。

舉個例子:
我們現在想做一個app,用來管理客戶資訊,實現簡單的CRUD功能(create/retrieve/update/delete),比如:

  • 獲取客戶資訊

  • 增加一個客戶

  • 刪除一個客戶

  • 更新客戶資訊

好啦,接下來我們就使用json-server完成這一系列動作吧!

安裝JSON-Server

npm install -g json-server//osx系統加'sudo'

新建一個資料夾同時cd它:

mkdircustomer-manager &&cdcustomer-manager

新建一個json檔案,然後存放一點資料進去:

touchcustomers.json
{
  "customers": [
    { "id": 1, "first_name": "John", "last_name": "Smith",  "phone": "219-839-2819" }
  ]
}

開啟json-server功能

所有你要做的事情只是讓json-server指向這個customers.json就ok啦!

json-servercustomers.js

然後出現這個提示就ok啦!

另外,JSON-Server很酷的一點就是支援各種GET/POST/PUT/DELETE的請求。
看幾個例子:

//GET
fetch('http://localhost:3000/tasks/')
  .then(function(response) {
    return response.json()
  }).then(function(json) {
    console.log('parsed json: ', json)
  }).catch(function(ex) {
    console.log('parsing failed: ', ex)
  });


//POST
fetch('http://localhost:3000/tasks/', {
  method: 'post',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
       "title":   "Add a blogpost about Angular2",
       "dueDate": "2015-05-23T18:25:43.511Z",
       "done": false
   })
}).then(function(response) {
      return response.json()
    }).then(function(json) {
      console.log('parsed json: ', json)
    }).catch(function(ex) {
      console.log('parsing failed: ', ex)
    });
    
    
//PUT
fetch('http://localhost:3000/tasks/1', { //在url後面指定下id就好
  method: 'put',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
       "done": true
   })
}).then(function(response) {
      return response.json()
    }).then(function(json) {
      console.log('parsed json: ', json)
    }).catch(function(ex) {
      console.log('parsing failed: ', ex)
    });
    
    
//DELETE
fetch('http://localhost:3000/tasks/1', {
method: 'delete'
}).then(function(response) {
   return response.json()
 }).then(function(json) {
   console.log('parsed json: ', json)
 }).catch(function(ex) {
   console.log('parsing failed: ', ex)
 });

JSON-Server基本就是這樣啦!接下來介紹另一個神器~

Faker.js

如果要自己瞎編API資料的話也是比較煩惱,用faker.js就可以輕鬆解決這個問題啦!他可以幫助你自動生成大量fake的json資料,作為後端資料~

安裝faker.js

還是使用npm來安裝faker.js:

npminstallfaker

現在我們用javascript生成一個包含50個客戶資料的json檔案:

//customers.js
var faker = require('faker')

function generateCustomers () {
  var customers = []

  for (var id = 0; id < 50; id++) {
    var firstName = faker.name.firstName()
    var lastName = faker.name.firstName()
    var phoneNumber = faker.phone.phoneNumberFormat()

    customers.push({
      "id": id,
      "first_name": firstName,
      "last_name": lastName,
      "phone": phoneNumber
    })
  }

  return { "customers": customers }
}

// 如果你要用json-server的話,就需要export這個生成fake data的function
module.exports = generateCustomers

然後讓json-server指向這個js檔案:

json-servercustomers.js

這樣你就可以在http://localhost:3000/customers裡看到50個客戶資料了。
更多faker.js屬性可以檢視這裡:
https://github.com/marak/Fake...

轉載於:https://segmentfault.com/a/1190000008574028