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

如何在Axios错误对象中获取POST请求的请求体?

解决Axios POST请求失败时获取请求体的问题

Axios默认不会在error.request里直接保存原始请求体,要实现失败时记录请求体,有两种常用方案:

方案一:手动提前保存请求体

发起请求前把请求体单独存储,捕获错误时直接取用:

const requestData = { test: data };
try {
  await axios.post('http://example.com', requestData, { 'content-type': 'application/json' })
} catch (error) {
  console.log(error.response.data);
  console.log(requestData); // 直接使用提前保存的请求体
}

方案二:通过拦截器统一挂载请求体

利用Axios的请求拦截器,给每个请求的配置对象添加自定义字段,后续在错误中就能直接获取:

// 全局添加请求拦截器
axios.interceptors.request.use(config => {
  // 将请求体挂载到config的自定义属性上
  config.requestBody = config.data;
  return config;
}, error => {
  return Promise.reject(error);
});

// 发起请求
try {
  await axios.post('http://example.com', { test: data }, { 'content-type': 'application/json' })
} catch (error) {
  console.log(error.response.data);
  console.log(error.config.requestBody); // 从配置对象中取出请求体
}

补充说明

  • error.request.data之所以是undefined,是因为error.request对应浏览器的XMLHttpRequest实例或Node.js的http.ClientRequest实例,这些原生对象不会自动保存序列化前的原始请求体,Axios也没有默认把原始数据挂载到这个属性上。
  • 如果请求体是经过序列化的格式(比如JSON字符串、FormData),拦截器方案同样适用,config.data会保留序列化后的内容,按需处理即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 02:25:53