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

带/:id后缀的HTTP PATCH请求异常:DELETE正常但返回404

问题解决:PATCH请求出现undefined的404错误

核心原因

你在handleUpdateSubmit函数内部重新声明了一个同名的trip变量:

const trip = {dateStop}

这个局部变量直接覆盖了外部作用域中包含_id的trip对象,导致后续拼接URL时,trip._id取的是这个局部对象的属性——而它根本没有_id,所以出现undefined,最终请求URL变成http://localhost:4000/api/tracks/undefined,触发404。

修复方案

方案1:避免变量名冲突,保留外部trip的_id

修改局部变量名,同时把外部的trip._id加入到提交对象中(确保后端能匹配到对应数据):

const handleUpdateSubmit = async (e) => {
  e.preventDefault()
  // 改名局部变量,避免覆盖外部trip
  const updatedTrip = { dateStop, _id: trip._id }
  
  const response = await fetch(`http://localhost:4000/api/tracks/${trip._id}`, {
    method: "PATCH",
    body: JSON.stringify(updatedTrip),
    headers: {
        "content-type": "application/json"
    }
  })
  const json = await response.json()

  if(!response.ok) {
    setError(json.error)
    console.log(updatedTrip)
  }
  if(response.ok) {
    setError(null)
    setParagraphClicked(false)
    // 更新操作对应UPDATE_TRIP类型,而非CREATE_TRIP
    dispatch({type: "UPDATE_TRIP", payload: json})
  }
}

方案2:直接使用外部trip的_id,不声明同名局部变量

如果仅需提交dateStop字段,直接在fetch中调用外部的trip._id即可:

const handleUpdateSubmit = async (e) => {
  e.preventDefault()
  const updateData = { dateStop }
  
  const response = await fetch(`http://localhost:4000/api/tracks/${trip._id}`, {
    method: "PATCH",
    body: JSON.stringify(updateData),
    headers: {
        "content-type": "application/json"
    }
  })
  const json = await response.json()

  if(!response.ok) {
    setError(json.error)
    console.log(updateData)
  }
  if(response.ok) {
    setError(null)
    setParagraphClicked(false)
    dispatch({type: "UPDATE_TRIP", payload: json})
  }
}

额外优化建议

  • 用模板字符串拼接URL更简洁易读:`http://localhost:4000/api/tracks/${trip._id}`
  • 更新操作的dispatch类型需改为UPDATE_TRIP,否则Redux状态管理会出现逻辑错误

内容的提问来源于stack exchange,提问作者Kamil K.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 11:48:25