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

如何修复AxiosError: Request failed with status code 400请求错误

排查与修复 Axios 400 错误

错误信息

Request failed with status code 400
AxiosError: Request failed with status code 400
at settle (http://localhost:3000/static/js/bundle.js:49658:12)
at XMLHttpRequest.onloadend (http://localhost:3000/static/js/bundle.js:48358:66)

问题代码

axios.get('https://64dc3b32e64a8526a0f64c9f.mockapi.io/todos'+id)
    .then(res => setData(res.data))
    .catch(err => console.log(err))
  },[])
  function handleSubmit(event) {
    event.preventDefault()
    axios.put('https://64dc3b32e64a8526a0f64c9f.mockapi.io/todos' +id, data)

问题排查与修复方案

1. URL 拼接缺失斜杠(最可能触发错误的原因)

请求 URL 拼接时,todos 和 id 之间未添加斜杠,会生成类似 https://xxx.mockapi.io/todos123 的无效路径,MockAPI 无法识别该地址,直接返回 400 错误。

修复代码:
在 todos 与 id 之间补上斜杠:

// GET 请求修复
axios.get('https://64dc3b32e64a8526a0f64c9f.mockapi.io/todos/' + id)
    .then(res => setData(res.data))
    .catch(err => console.log(err))

// PUT 请求修复
axios.put('https://64dc3b32e64a8526a0f64c9f.mockapi.io/todos/' + id, data)

2. 补全依赖校验与错误处理

  • useEffect 依赖数组为空,若 id 是动态赋值的,组件初始化时可能 id 还未定义,导致请求 URL 变为 todos/undefined,触发 400。需把 id 加入依赖数组,并先校验 id 合法性再发起请求:
useEffect(() => {
  if (id) {
    axios.get('https://64dc3b32e64a8526a0f64c9f.mockapi.io/todos/' + id)
      .then(res => setData(res.data))
      .catch(err => console.log(err))
  }
}, [id])
  • PUT 请求未添加错误捕获逻辑,无法获取具体错误详情,建议补充:
function handleSubmit(event) {
  event.preventDefault()
  if (!id || !data) return
  axios.put('https://64dc3b32e64a8526a0f64c9f.mockapi.io/todos/' + id, data)
    .then(res => console.log('更新成功', res))
    .catch(err => console.error('更新失败', err.response?.data || err.message))
}

3. 校验请求数据格式

MockAPI 的 todos 接口通常要求固定字段(如 title、completed),若 data 对象缺少必填字段或格式不符,也会返回 400。可以先打印 data 确认结构,或对照 MockAPI 后台的字段要求调整数据格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 00:45:00