JSON Server
简介
使用JSON Server可以快速建立一个虚拟的数据库,并且支援开发中最常用的 GET、POST、PUT、PATCH、DELETE、OPTIONS 等 request method。
建立JSON-Server
在VS Code中建立一个db.json档案,将模拟的数据库数据输入在上面(下方使用JSON-Server GitHub範例)。
{ "posts": [ { "id": 1, "title": "json-server", "author": "typicode" } ], "comments": [ { "id": 1, "body": "some comment", "postId": 1 } ], "profile": [ { "name": "typicode" } ] }
在专案中安装JSON-Server
npm install -g json-serveryarn add json-server
启动JSON-Server
Step 1 : 打开pakeage.json
{ "dependencies": { "json-server": "^0.16.1" }}
Step 2 : 加入start与license命令
{ "dependencies": { "json-server": "^0.16.1" }, "scripts":{ "start": "json-server --watch db.json --port 3004" //预设3000可以藉由 --port 来改变端口号 }, "license": "MIT"}
json-server --watch db.json
预设端口是3000可以藉由 --port来改变自定义的端口号
Step 3 : 使用yarn start启动JSON-Server
结果 :
JSON-Server Method
使用Postman 来确认JSON-Server的数据库状况。
GET (取得资料)
POST (新增资料)
使用GET来取得变化后的数据 :
PUT (更新资料)
更改id:2的数据,将"title":Post Try更改为"title":PUT Try
使用GET来取得变化后的数据 :
DELETE (删除资料)
将id:2删除 :
参考资料 :
GitHub-json-server
使用 JSON Server 快速模拟 Restful API