今天發現了一個神器——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它:
mkdir customer-manager && cd customer-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-server customers.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:
npm install faker
現在我們用javascript生成一個包含50個客戶數據的json文件:
//customers.js
var faker = require('faker')
functiongenerateCustomers () {
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-server customers.js
這樣你就可以在http://localhost:3000/customers里看到50個客戶數據了。
更多faker.js屬性可以查看這里:
https://github.com/marak/Fake...
好啦,基本就是這樣啦,happy coding!