我的 React 之旅:第 19 天

我的 react 之旅:第 19 天

使用 json api 和模拟服务器进行练习

使用 json-server 是模拟后端服务器并练习 get、post、put、patch 和 delete 等 api 交互的好方法。

什么是 json-server

一个工具,允许您快速创建一个模拟服务器来使用json数据库。非常适合原型设计和测试 api,无需功能齐全的后端。

设置和安装

1。先决条件:node.js

确保您的系统上安装了 node.js。验证使用:

node -vnpm -v

2。安装 json-server

使用 npm 全局安装:

npm install -g json-server@0.17.4

如何使用 json-server

1。启动服务器
使用一些初始数据在工作目录中创建 db.json 文件。示例:

{  "posts": [    { "id": 1, "title": "first post", "content": "hello world!" },    { "id": 2, "title": "second post", "content": "learning json-server" }  ]}

启动服务器并观察 db.json 文件中的更改:

json-server --watch db.json

默认情况下,服务器将在http://localhost:3000.运行

2。探索端点
服务器自动为 db.json 中的每个集合创建 restful 端点:

get /posts → 获取所有帖子get /posts/1 → 获取 id 为 1 的帖子post /posts → 添加新帖子put /posts/1 → 将整个帖子替换为 id 1patch /posts/1 → 更新帖子中 id 为 1 的特定字段delete /posts/1 → 删除 id 为 1 的帖子

使用邮递员

postman 是一个用于发出http 请求来测试api的工具。以下是如何使用 postman 执行每个操作:

1。 get(获取数据)

请求类型:get网址:http://localhost:3000/posts获取帖子列表。

2。 post(添加新数据)

请求类型:post网址:http://localhost:3000/posts标头:内容类型:application/json正文(json):

{  "id": 3,  "title": "new post",  "content": "this is a new post"}

将新帖子添加到帖子集合中。

3。 put(替换整个资源)

请求类型:put网址:http://localhost:3000/posts/2/2标头:内容类型:application/json

正文(json):
{
“title”: “更新标题”
}

结果:用提供的数据替换整个资源。

之前:

{  "id": 2,  "title": "second post",  "content": "learning json-server"}

之后:

{  "title": "updated title"}

4。 patch(更新特定字段)

请求类型:patch网址:http://localhost:3000/posts/1/1标头:内容类型:application/json正文(json):

{  "content": "updated content"}

结果: 仅更新资源中的指定字段。

之前:

{  "id": 1,  "title": "first post",  "content": "hello world!"}

之后:

{  "id": 1,  "title": "First Post",  "content": "Updated Content"}

5。 delete(删除数据)

请求类型:删除网址:http://localhost:3000/posts/1/1删除 id 为 1 的帖子。

put 和 patch 之间的主要区别

放置

替换整个资源。 省略正文中未包含的任何字段。

补丁

仅更新指定字段。保留正文中未提及的字段。

结论

我学到了什么:

安装并使用 json-server 创建模拟 api 服务器。练习了基本的 api 操作:get、post、put、patch、delete。了解 put 和 patch 之间的区别。

第 19 天崩溃了。

以上就是我的 React 之旅:第 19 天的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1499594.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月19日 21:53:30
下一篇 2025年12月19日 21:53:46

相关推荐

发表回复

登录后才能评论
关注微信