5

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 Answers1

4

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>
Phil
  • 157,677
  • 23
  • 242
  • 245