首页 >web前端 >js教程 >我的 React 之旅:第 19 天

我的 React 之旅:第 19 天

Patricia Arquette
Patricia Arquette原创
2024-12-22 07:43:44933浏览

My React Journey: Day 19

使用 JSON API 和模拟服务器进行练习

使用 json-server 是模拟后端服务器并练习 GET、POST、PUT、PATCH 和 DELETE 等 API 交互的好方法。

什么是 json-server

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

设置和安装

1。先决条件:Node.js

  • 确保您的系统上安装了 Node.js。验证使用:
node -v
npm -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 1
  • PATCH /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
  • 标头:内容类型:application/json
  • 正文(JSON):
    {
    "title": "更新标题"
    }

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

之前:

{
  "id": 2,
  "title": "Second Post",
  "content": "Learning JSON-Server"
}

之后:

{
  "title": "Updated Title"
}

4。 PATCH(更新特定字段)

  • 请求类型:PATCH
  • 网址:http://localhost:3000/posts/1
  • 标头:内容类型:application/json
  • 正文(JSON):
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(删除数据)

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

PUT 和 PATCH 之间的主要区别

放置

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

补丁

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

结论

我学到了什么:

  • 安装并使用 json-server 创建模拟 API 服务器。
  • 练习了基本的 API 操作:GET、POST、PUT、PATCH、DELETE。
  • 了解 PUT 和 PATCH 之间的区别。

第 19 天崩溃了。

以上是我的 React 之旅:第 19 天的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn