我的 React 之旅:第 19 天

来源:undefined 2025-01-22 02:08:48 1029

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

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

什么是 json-server

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

设置和安装

1。先决条件:node.js

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

1

2

node -v

npm -v

登录后复制

2。安装 json-server

使用 npm 全局安装:

1

npm install -g json-server@0.17.4

登录后复制

如何使用 json-server

1。启动服务器

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

1

2

3

4

5

6

{

"posts": [

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

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

]

}

登录后复制
启动服务器并观察 db.json 文件中的更改:

1

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):

1

2

3

4

5

{

"id": 3,

"title": "new post",

"content": "this is a new post"

}

登录后复制
将新帖子添加到帖子集合中。

3。 put(替换整个资源)

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

正文(json):

{

"title": "更新标题"

}

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

之前:

1

2

3

4

5

{

"id": 2,

"title": "second post",

"content": "learning json-server"

}

登录后复制

1

2

3

{

"title": "updated title"

}

登录后复制

4。 patch(更新特定字段)

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

1

2

3

{

"content": "updated content"

}

登录后复制

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

之前:

1

2

3

4

5

{

"id": 1,

"title": "first post",

"content": "hello world!"

}

登录后复制

之后:

1

2

3

4

5

{

"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 天的详细内容,更多请关注php中文网其它相关文章!

最新文章