使用 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(更新特定字段)
{ "content": "updated content" }
结果: 仅更新资源中的指定字段。
之前:
{ "id": 1, "title": "first post", "content": "hello world!" }
之后:
{ "id": 1, "title": "First Post", "content": "Updated Content" }
5。 delete(删除数据)
put 和 patch 之间的主要区别
放置
补丁
我学到了什么:
第 19 天崩溃了。
以上就是我的 React 之旅:第 19 天的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号