how to get axios error post/request payload on catch

Viewed 276

when I catch an axios error, how can i get the request body? (what I've sent to the server, not the server response)

example of what i want to achieve

axios.post("url",{
    name:jesus
}).then((response) => {
    ....
}).catch((error) => {
    console.log(error.request.body)  //name:jesus
})
1 Answers

You can access the original request data via error.config.data. Note that it will be the serialised format (in your case JSON) so you may need to parse it back into a JS object.

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);
  });
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

Related