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

Node.js中PUT请求更新JSON数据失败,遇404及JSON解析错误求助

解决PUT请求404及JSON解析错误问题

错误根源

  • 404错误:前端PUT请求地址/venteliste与后端定义的路由/venteliste/:id不匹配,服务器找不到对应处理逻辑,返回404状态码。
  • JSON解析错误:服务器返回404时默认返回HTML格式的错误页面,前端用response.json()解析HTML内容,触发语法错误。

前端代码修复

  1. 修正PUT请求URL,带上目标数据的ID,匹配后端路由规则
  2. 优化请求数据,仅传递需要更新的check字段,无需发送整个数组
  3. 调整UI更新时机,确保请求成功后再修改页面状态,避免前后端数据不一致

修改后的前端代码:

async function checkKolonist(evt) {
  let dataId = evt.target.parentNode.parentNode.getAttribute("data-id");
  const listItem = evt.target.parentNode.parentNode;

  // 获取目标项当前状态
  fetch(`/venteliste/${dataId}`)
    .then(response => response.json())
    .then(targetItem => {
      const newCheckStatus = targetItem.check !== 1 ? 1 : 0;
      
      // 发送PUT请求更新单个项的check状态
      fetch(`/venteliste/${dataId}`, {
        method: 'PUT',
        body: JSON.stringify({ check: newCheckStatus }),
        headers: {
          'Content-Type': 'application/json'
        }
      })
      .then(response => {
        if (!response.ok) throw new Error('更新失败');
        return response.json();
      })
      .then(updatedData => {
        // 请求成功后更新UI状态
        if (newCheckStatus === 1) {
          listItem.classList.remove("notchecked");
          listItem.classList.add("checked");
        } else {
          listItem.classList.add("notchecked");
          listItem.classList.remove("checked");
        }
        console.log('Data updated successfully:', updatedData);
      })
      .catch(error => console.error('Error updating data:', error));
    })
    .catch(error => console.error('Error fetching data:', error));
}

后端代码修复

  1. 直接使用路由参数:id匹配目标数据项,无需从请求体中获取data-id
  2. 仅更新目标项的check字段,避免覆盖其他数据
  3. 确保所有响应均为JSON格式,避免返回HTML错误页

修改后的后端代码:

app.put('/venteliste/:id', updateKolonisterHandler);

function updateKolonisterHandler(request, response) {
  const kolonistId = parseInt(request.params.id);
  const { check } = request.body;

  // 查找目标项索引
  const targetIndex = venteliste.findIndex(item => item.id === kolonistId);
  
  if (targetIndex !== -1) {
    // 仅更新check字段
    venteliste[targetIndex].check = check;
    response.status(200).json({ 
      status: 'success', 
      message: 'Kolonist updated successfully',
      data: venteliste[targetIndex]
    });
  } else {
    // 返回JSON格式的错误信息
    response.status(404).json({ 
      status: 'error', 
      message: `Kolonist ID ${kolonistId} not found in venteliste` 
    });
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 12:58:12