使用 json-server 是模拟后端服务器并练习 GET、POST、PUT、PATCH 和 DELETE 等 API 交互的好方法。
什么是 json-server?
1。先决条件:Node.js
node -v npm -v
2。安装 json-server
npm install -g json-server@0.17.4
1。启动服务器
使用一些初始数据在工作目录中创建 db.json 文件。示例:
{ "posts": [ { "id": 1, "title": "First Post", "content": "Hello World!" }, { "id": 2, "title": "Second Post", "content": "Learning JSON-Server" } ] }
json-server --watch db.json
2。探索端点
服务器自动为 db.json 中的每个集合创建 RESTful 端点:
Postman 是一个用于发出HTTP 请求来测试API的工具。以下是如何使用 Postman 执行每个操作:
1。 GET(获取数据)
2。 POST(添加新数据)
{ "id": 3, "title": "New Post", "content": "This is a new post" }
3。 PUT(替换整个资源)
正文(JSON):
{
"title": "更新标题"
}
结果:用提供的数据替换整个资源。
之前:
{ "id": 2, "title": "Second Post", "content": "Learning JSON-Server" }
之后:
{ "title": "Updated Title" }
4。 PATCH(更新特定字段)
node -v npm -v
结果: 仅更新资源中的指定字段。
之前:
npm install -g json-server@0.17.4
之后:
{ "posts": [ { "id": 1, "title": "First Post", "content": "Hello World!" }, { "id": 2, "title": "Second Post", "content": "Learning JSON-Server" } ] }
5。 DELETE(删除数据)
PUT 和 PATCH 之间的主要区别
放置
补丁
我学到了什么:
第 19 天崩溃了。
以上是我的 React 之旅:第 19 天的详细内容。更多信息请关注PHP中文网其他相关文章!