本日发现了一个神器——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文件,然后寄存一点数据进去:
touch customers.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')
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-server customers.js
如许你就能够在http://localhost:3000/customers里看到50个客户数据了。
更多faker.js属性能够检察这里:
https://github.com/marak/Fake…
好啦,基础就是如许啦,happy coding!