三步使用 JSON Server 模拟 API

来源:互联网 发布:linux scp定义算法 编辑:程序博客网 时间:2024/06/06 12:39

有了设计图之后,后端的 API 往往也才刚刚开始做,在这个时候,能有一个原型工具模拟一份 API 会让一切过的开心很多。

安装

第一步当然是安装啦

Homebrew

Homebrew 是 Mac 上的第三方库管理工具,我们使用 Homebrew 来安装 Node.js

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Node.js

brew install node

json-server

npm install -g json-server

创建 db.json

找个你喜欢的目录,创建 db.json,里面包含你需要的数据模型

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

随后,利用 json-server --watch db.json 来启动 Server

测试

启动起来之后,json-server 会根据你的 db.json 自动建立 RESTful API,以上面的 db.json 的 post 为例

GET    /posts  GET    /posts/1  POST   /posts  PUT    /posts/1  PATCH  /posts/1  DELETE /posts/1

更深入的使用方式,可以参考 json-server 的官方文档。

原创粉丝点击