简介
json-server是一个很好的模拟后端数据接口的工具。只需要提供一个json文件,或者写几行简单的js脚本就可以模拟出RESTful API的接口。
github
基本使用
- 全局安装
sudo npm install -g json-server
- 创建json文件
db.json
{ "user": {"name": "Tom"}, "book": [ {"id": 1, "name": "Thinking in JAVA", "price": 99.99}, {"id": 2, "name": "Core JAVA", "price": 66.99} ] }
注
:user
和book
,必须是对象或者数组,否则启动会报错 - 运行
json-server --watch db.json
注
:--watch
会监听db.json的变化,自动同步
如图运行成功
- 更多命令
json-server -h
RESTful
对于POST
、PUT
、PATCH
或DELETE
请求,这些更改将使用lowdb自动和安全地保存到db.json
- json-server提供了RESTful风格的api,路由规则如下
GET /book GET /book/1 POST /book PUT /book/1 PATCH /book/1 DELETE /book/1
- HTTP Request
### books GET http://localhost:3000/book Accept: application/json ### find book GET http://localhost:3000/book/1 Accept: application/json ### add book POST http://localhost:3000/book Content-Type: application/json { "id": 3, "name": "JAVA 8 in Action", "price": 66.66 } ### update book PUT http://localhost:3000/book/3 Content-Type: application/json { "id": 3, "name": "JAVA 8 in Action", "price": 66.77 } ### delete book DELETE http://localhost:3000/book/3
- more
json-server提供了非常多的路由方式,更多路由:routes