如何修复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
相关产品推荐
相关产品推荐

