You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在React项目的JSON Server中访问评论属性并提交评论

解决方案

1. 提交评论到指定名言的comments数组

要把用户提交的评论存入对应名言的comments属性,需要向JSON Server发送PATCH请求更新目标名言的资源:

// React中处理评论提交的示例函数
const submitComment = async (quoteId, commentContent) => {
  // 先获取目标名言的当前数据
  const quoteRes = await fetch(`http://localhost:3001/quotes/${quoteId}`);
  const targetQuote = await quoteRes.json();

  // 构造更新后的评论数组(保留原有评论,追加新评论)
  const newComments = [
    ...targetQuote.comments,
    { id: Date.now(), content: commentContent } // 给新评论加唯一ID
  ];

  // 发送PATCH请求更新数据
  await fetch(`http://localhost:3001/quotes/${quoteId}`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ comments: newComments })
  });
};

2. 通过嵌套路径获取评论

如果你想通过http://localhost:3001/quotes/1/comments直接获取对应名言的评论,有两种可行方式:

方式一:从名言资源中提取

直接请求目标名言的完整数据,再取出comments字段即可:

const fetchComments = async (quoteId) => {
  const res = await fetch(`http://localhost:3001/quotes/${quoteId}`);
  const quote = await res.json();
  return quote.comments;
};

方式二:配置JSON Server自定义路由

如果要严格通过嵌套路径返回评论,在项目根目录创建routes.json文件:

{
  "/quotes/:id/comments": "/quotes/:id/comments"
}

启动JSON Server时指定路由文件:

json-server --watch db.json --routes routes.json

之后发送GET请求到http://localhost:3001/quotes/1/comments,就能直接拿到该名言的评论数组。

关键注意点

  • 新评论添加唯一ID(比如Date.now()),方便后续做删除、编辑操作
  • PATCH请求只会更新comments字段,不会修改名言的其他属性
  • 必须设置请求头Content-Type: application/json,否则JSON Server无法解析请求体

内容的提问来源于stack exchange,提问作者ali pasha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 21:01:41