如何在 catch 上获取 axios 错误发布/请求负载

Jes*_*hen 6 javascript post node.js reactjs axios

当我捕获 axios 错误时,如何获取请求正文?(我发送到服务器的内容,而不是服务器响应)

我想要实现的目标的例子

axios.post("url",{
    name:jesus
}).then((response) => {
    ....
}).catch((error) => {
    console.log(error.request.body)  //name:jesus
})
Run Code Online (Sandbox Code Playgroud)

Phi*_*hil 7

您可以通过访问原始请求数据error.config.data。请注意,它将是序列化格式(在您的例子中为 JSON),因此您可能需要将其解析回 JS 对象。

axios
  .post("http://httpbin.org/status/400", {
    name: "jesus",
  })
  .then((res) => {
    console.log("response", res);
  })
  .catch((error) => {
    const data = JSON.parse(error.config.data);
    console.error("request data", data);
  });
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Run Code Online (Sandbox Code Playgroud)