登录
首页 >  文章 >  前端

我的 React 之旅:第 19 天

来源:dev.to

时间:2024-12-22 10:52:12 145浏览 收藏

目前golang学习网上已经有很多关于文章的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《我的 React 之旅:第 19 天》,也希望能帮助到大家,如果阅读完后真的对你学习文章有帮助,欢迎动动手指,评论留言并分享~

我的 React 之旅:第 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/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 天》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>