Node.js中PUT请求更新JSON数据失败,遇404及JSON解析错误求助
解决PUT请求404及JSON解析错误问题
错误根源
- 404错误:前端PUT请求地址
/venteliste与后端定义的路由/venteliste/:id不匹配,服务器找不到对应处理逻辑,返回404状态码。 - JSON解析错误:服务器返回404时默认返回HTML格式的错误页面,前端用
response.json()解析HTML内容,触发语法错误。
前端代码修复
- 修正PUT请求URL,带上目标数据的ID,匹配后端路由规则
- 优化请求数据,仅传递需要更新的
check字段,无需发送整个数组 - 调整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)); }
后端代码修复
- 直接使用路由参数
:id匹配目标数据项,无需从请求体中获取data-id - 仅更新目标项的
check字段,避免覆盖其他数据 - 确保所有响应均为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
相关产品推荐
相关产品推荐

