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

React中JSON Server更新路由配置是否正确?请求端点无法访问

React + JSON Server 数据更新端点访问问题修复

问题场景

在React项目中调用JSON Server更新文章的点赞数和评论时,始终无法正确访问请求端点,调整URL后仍报错。

错误原因分析

  1. addUpvote函数问题:PUT请求缺少完整域名,且错误指向子路径/articles/${id}/upvotes——JSON Server不支持通过子路径单独更新字段,必须直接请求完整的文章资源路径。
  2. addComment函数问题:错误指向子路径/articles/${id}/comments,不符合JSON Server的资源更新规则,同时state更新逻辑存在错误。

修正后的代码

修正addUpvote函数

const addUpvote = async () => {
  try {
    // 补全完整域名,直接请求文章资源路径
    const response = await axios.put(`http://localhost:5000/articles/${id}`, {
      ...articleInfo,
      upvotes: articleInfo.upvotes + 1
    });
    setArticleInfo(response.data);
  } catch (err) {
    console.error('点赞更新失败:', err);
  }
};

修正addComment函数

const addComment = async () => {
  if (!author.trim() || !text.trim()) return; // 过滤空评论
  try {
    const updatedComments = [...articleInfo.comments, { author, text }];
    // 直接更新整个文章资源,传递包含新评论的完整对象
    const response = await axios.put(`http://localhost:5000/articles/${id}`, {
      ...articleInfo,
      comments: updatedComments
    });
    setArticleInfo(response.data);
    setAuthor("");
    setText("");
  } catch (err) {
    console.error('评论添加失败:', err);
  }
};

额外优化建议

  • 配置axios全局baseURL,避免重复写域名:
    axios.defaults.baseURL = 'http://localhost:5000';
    
    之后请求只需写相对路径,比如axios.put(/articles/${id}, ...)
  • 所有异步请求添加try/catch捕获错误,方便排查问题
  • JSON Server核心规则:更新资源需通过PUT /资源名/:id传递完整或部分字段,不支持子路径单独更新嵌套字段

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 21:11:28