Axios error get body

I am sending a status code 422 from my backend code with response body which contains the description of the error. I am using axios post as below to post a request: post: function(url, reqBody) {...

I am sending a status code 422 from my backend code with response body which contains the description of the error. I am using axios post as below to post a request:

post: function(url, reqBody) {
    const request = axios({
        baseURL: config.apiUrl,
        url: url,
        headers: {
            'Content-Type': 'application/json',
            'Authorization': sessionStorage.getItem('token')
        },
        method: 'POST',
        data: reqBody,
        responseType: 'json'
    });
    return request
        .then((res) => {
            return res;
        })
        .catch((error) => {
            console.log(error);
            return error;
        })
}

The problem is when backend is returning error code 422, the error object I am catching has no information about response body. Is there any way I can retrieve the error text?

Talha Awan's user avatar

Talha Awan

4,5284 gold badges24 silver badges40 bronze badges

asked Jul 10, 2017 at 17:00

Amol Aggarwal's user avatar

Amol AggarwalAmol Aggarwal

2,5142 gold badges23 silver badges32 bronze badges

I had this same issue and the answer (as per Axios >= 0.13) is to specifically check error.response.data:

axios({
    ...
}).then((response) => {
    ....
}).catch((error) => {
    if( error.response ){
        console.log(error.response.data); // => the response payload 
    }
});

See here for more details.

answered Jul 23, 2017 at 22:45

JoeTidee's user avatar

0

The «body» of an AXIOS error response depends from the type of response the request had.

If you would like full details about this issue you can see this blogpost: How to catch the body of an error in AXIOS.

In summary AXIOS will return 3 different body depending from the error:

  1. Wrong request, we have actually done something wrong in our request (missing argument, bad format), that is has not actually been sent. When this happen, we can access the information using error.message.

    axios.get('wrongSetup')
    .then((response) => {})
    .catch((error) => {
        console.log(error.message);
    })
    
  2. Bad Network request: This happen when the server we are trying to reach does not respond at all. This can either be due to the server being down, or the URL being wrong.
    In this case, we can access the information of the request using error.request.

    axios.get('network error')
    .then((response) => {})
    .catch((error) => {
        console.log(error.request );
    });
    
  3. Error status: This is the most common of the request. This can happen with any request that returns with a status that is different than 200. It can be unauthorised, not found, internal error and more. When this error happen, we are able to grasp the information of the request by accessing the parameter specified in the snippets below. For the data (as asked above) we need to access the error.response.data.

    axios.get('errorStatus')
    .then((response) => {})
    .catch((error) => { 
         console.log(error.response.data);  
         console.log(error.response.status);  
         console.log(error.response.headers); 
     })
    

answered Sep 4, 2020 at 15:05

Zelig880's user avatar

Zelig880Zelig880

4304 silver badges6 bronze badges

2

For those using await/async and Typescript

try {
    const response = await axios.post(url, body)
} catch (error) {
    console.log(error.response.data);
}

answered Nov 4, 2020 at 4:49

Yayo Arellano's user avatar

For react native it just worked for me

api.METHOD('endPonit', body)
  .then(response => {
   //...
  })
  .catch (error => {
    const errorMessage = JSON.parse(error.request.response)
    console.log(errorMessage.message)
  })

answered Jan 2, 2021 at 21:03

Rafael Inácio's user avatar

We can check error.response.data as @JoeTidee said. But in cases response payload is blob type? You can get error response body with the below code.

axios({
    ...
}).then((response) => {
    ....
}).catch(async (error) => {
    const response = error.response
    if(typeof response.data.text === function){
        console.log(await response.data.text()); // => the response payload 
    } else {
        console.log(response.data)
    }
});

answered Aug 13, 2021 at 5:44

TopW3's user avatar

TopW3TopW3

1,4691 gold badge7 silver badges14 bronze badges

I am returning a string from backend but expecting a json as response type. So I need to return an object instead of string for axios to process it properly.

answered Jul 10, 2017 at 18:34

Amol Aggarwal's user avatar

Amol AggarwalAmol Aggarwal

2,5142 gold badges23 silver badges32 bronze badges

In my case I wanted to retrieve a response 404 error message (body).
I got body with error.response.data but I couldn’t display it because the type was ArrayBuffer.

Solution:

axios.get(url, { responseType: 'arraybuffer' }).then(
   response => {...},
   error => {
      const decoder = new TextDecoder()
      console.log(decoder.decode(error.response.data))
   }
)

Related posts:
Converting between strings and ArrayBuffers

answered Jul 4, 2022 at 10:00

Jakub Słowikowski's user avatar

Mr_SC

If you have been searching the web for some information about AXIOS error messages, and would like to understand how to use them, then you have come to the right place.

TLTR; Find the code snippets in the following section

If you search the web on this topic, all you can find is:

  • catching error body using axios post
  • Unable to catch the body of error
  • JS Axios – how to get response body in event of error?
  • How to see axios error response JSON in React

The list could have gone on and on, but they all ask for the sample simple question:

How can someone get the actual error information coming from a bad request made with AXIOS.

In this post we are going to provide information on “why” so many people ask for information, and “how” this information can be found.

Why so many people ask for this

If you have ever worked with an api, you perfectly know that request not always go to plan. You hope to always get a lovely response with a status of 200, but this does not always happens.

In many instances the status of our request may return some kind of error (400, 500), and when this happens we would like to be able to have a readable error message.

axios.get('EndpointWithAuthorizedError')
    .then((response) => {})
    .catch((error) => {
        console.log(error);
    })

Enter fullscreen mode

Exit fullscreen mode

Unfortunately if the above would ever fail with a meaningful error, we would still see this within our console, as the variable passed by the catch statement seem to be of type “string”.

Error: Request failed with status code 401

Enter fullscreen mode

Exit fullscreen mode

This is actually the main reason why so many people are “forced” to ask for help.

How can we process AXIOS error message

There is actually no magic when processing the error messages. In fact, the catch is in the fact that the variable received by the catch statement seem to be a string, but in reality it is not.

The AXIOS error message can actually return 3 different structure, depending from what kind of failure it has (crazy right… I thought that too).

Error in setting up the request

This error can happen if we have made an actual mistake in setting up the AXIOS request. It could be something with the data passed, or a configuration setting.

When this happen we can actually find the information we need by accessing the message parameter of the catch.

axios.get('wrongSetup')
    .then((response) => {})
    .catch((error) => {
        console.log(error.message);
    })

//or using destructuring
axios.get('wrongSetup')
    .then((response) => {})
    .catch(({message) => {
        console.log(message);
    })

Enter fullscreen mode

Exit fullscreen mode

No response – Network Error

This scenario will take place when our request had no response at all. This can happen when the URL is incorrect, or if the receiving server is down.

When this happen we can access more information about our request bu accessing the request parameter. This will return the actual “request” information.

axios.get('network error')
     .then((response) => {})
     .catch((error) => {
         console.log(error. request );
     })
//or using destructuring
 axios.get('network error')
     .then((response) => {})
     .catch(({ request ) => {
         console.log( request );
     })

Enter fullscreen mode

Exit fullscreen mode

Request returned with an error status

This is one of the most common, or more specifically the one type of “error” that need to be manage to make sure our web applications function properly.

There are hundreds of status code differently than 200 (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status), that would fit in this category. I am going to list below the most important:

  • 400: Bad request
  • 401: Unauthorized
  • 403: Forbidden
  • 404: Not Found
  • 500: Internal Server error
  • 502: Bad Gateway

When any of the above happen, we would like to know more about the request. In this case there are more information provided to us: data, status, header.

axios.get('errorStatus')
     .then((response) => {})
     .catch((error) => { 
         console.log(error.response.data);  
         console.log(error.response.status);  
         console.log(error.response.headers); 
     })

//or using destructuring
 axios.get('errorStatus')
     .then((response) => {})
     .catch(({ response }) => { 
         console.log(response.data);  
         console.log(response.status);  
         console.log(response.headers);  
     })

Enter fullscreen mode

Exit fullscreen mode

With the above code, we will be able to get all the information we need about the response to our request. These includes the status code, the header and last but not least the data that the server has sent with the request.

When using any kind of API, the data parameter is going to include essential information, usually used for development purposes, but at times also good to show to the end users.

I hope to have saved you some time, and please feel free to comment, or provide suggestion to improve this post and help future readers

axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

Using the validateStatus config option, you can define HTTP code(s) that should throw an error.

axios.get('/user/12345', {
  validateStatus: function (status) {
    return status < 500; // Resolve only if the status code is less than 500
  }
})

Using toJSON you get an object with more information about the HTTP error.

axios.get('/user/12345')
  .catch(function (error) {
    console.log(error.toJSON());
  });

@oscarjlep

Summary

I already saw multiple posts regarding this issue, but was still unable to find what the problem really is. I have created generic method for throwing out JSON-errors on Java Spring backend:

public static void responseErrorJSON(ResourceResponse response, String errorMessage, String errorCode) throws IOException {
		response.setContentType("application/json");
		ErrorJSON result = new ErrorJSON();
		result.errorMessage = errorMessage;
		result.errorCode = errorCode;
		
		PrintWriter writer = null;
		response.setProperty(response.HTTP_STATUS_CODE, "500");
		writer = response.getWriter();

		writer.write(gson.toJson(result));
	}

I’m calling this method as such:

return axios.get(context.lr.url.getSalesOrderWithRows)
					.then(function(response) {
						if(typeof callback != "undefined")
							callback(response.data);
					}).catch(function (error) {
						console.log(error);
					});

…. but for some reason I’m unable to read message body sent by backend as correct JSON, even though it’s displaying just right within Chrome debugger:

image

Headers look like these, and I assume something here isn’t correct as:

image

What I’m getting with console.log(error1,error2) within catch is:

image

… so, basically I’m getting generic error-message-string which is generated by axios, but it doesn’t seem to contain any object properties such as «error.description» or such, nor error-json generated by backend. That «undefined» is the «error2», which I tried in order to check if it would have container the message body, but apparently doesn’t.

Context

  • axios version: e.g.: v0.17.0
  • Environment: e.g.: Liferay 6.2 / Java, chrome 64, windows 10

@emilyemorehouse

You should definitely be able to access that information. I don’t see anything jumping out at me that’s incorrect in your response or request info.

I’m not sure if it will help you or if you’ve already seen this info, but here’s an example test that passes:

    var data = {
      reason: 'Invalid something or other',
    };

    server = http.createServer(function (req, res) {
      res.statusCode = 500;
      res.setHeader('Content-Type', 'application/json;charset=utf-8');
      res.end(JSON.stringify(data));
    }).listen(4444, function () {
      axios.get('http://localhost:4444/').catch(function (error) {
        test.deepEqual(error.response.data, data);
        test.equal(error.response.status, 500);
        test.done();
      });
    });

You can see that you’re able to access the status and data via error.response.status or error.response.data.

Can you see if you can access either of those attributes? If you just log error, you’ll get the actual Error object, but you can drill down further. See this example:
screen shot 2018-02-19 at 9 22 13 am

@oscarjlep

I decided to try using node server to send the error in order to count out the possibility of Tomcat doing something weird, so I created following server script:

  server = http.createServer(function (req, res) {
     res.statusCode = 500;
     res.setHeader('Content-Type', 'application/json;charset=utf-8');
     res.setHeader('Access-Control-Allow-Origin', '*');
     res.setHeader('Access-Control-Allow-Credentials', 'false');
     res.end(JSON.stringify(data));
   }).listen(4444, function () {
   });

Then I call this with:

return axios.get("http://localhost:4444/", {withCredentials: false})
	.then(function(response) {
		if(typeof callback != "undefined")
			callback(response.data);
	}).catch(function (error) {
		console.log(error);
});

… and the outcome is exactly same, un-drillable string! Then I decided to check how it handles with Firefox and it seems that Firefox shows:

image

…. which is drillable!

This felt really strange, so I double checked the existance of error.response and yes, it really DID exist all the time. I must have had done something wrong initially when trying out checking the existance of response. This is very misleading as Chrome for some reason doesn’t seem to output as drillable (how is it even able to output object as plain string?).

I’d suggest considering separating the response object from mixed result object, so that callback function would have optional response object. Developer could write either function(result) or function(result, response).

Thank you for all the help!

@emilyemorehouse

Glad you got it working!

We’re doing a decent overhaul for v1.0.0, so I’ll definitely keep your suggestion in mind! I agree that it can be confusing as is.

@axios
axios

locked and limited conversation to collaborators

May 22, 2020

Axios is a JavaScript library that creates HTTP requests using either XMLHttpRequests in the browser or HTTP in the Node.js runtime by using the Promise API. These requests can use async/await syntax and can also use the .then() utilities for promise chaining, and the .catch() mechanism for error handling because these requests are promises. 

In this article, we are going to discuss how to handle errors from POST requests in AXIOS. There are two approaches to handling the error of post request in AXIOS:

  1. Async/Await Method
  2. Then and Catch Method   

Before start discusses or implements these above approaches, let’s set up our project and install some dependencies as well. Use the below commands or steps for creating Nodejs Project for implementing these approaches. 

Step 1: Create One Folder and open the folder in the command prompt. Use this command for initializing that folder.

npm init -y

Initializing Project

Step 2: Now, Install two important dependencies. First, Axios for making requests, and Second, Express for creating and running the server.

npm install axios express

Step 3: Create one Javascript file named app.js. In this file, we will be writing our code. Now, the Project Structure will something look like this.

Project Structure

Approach 1: Using Async/Await

Now, Let’s discuss the first approach to handling errors using Async/Await Method. Before starting implementation, let’s understand about async/await method. The await keyword is allowed in the function body when using the async function declaration to declare an async function. The async and await keywords make it possible to write promise-based, asynchronous behavior in a cleaner manner without having to explicitly configure promise chains.

Syntax:

app.get('/endpointURL', async (req, res) => {
 try {
     const result = await axios.get('/api-url');
       // Work here with result
 } catch (err) {
     // Error handling here
    return res.status(401).send(err.message);
 }
})

Implementation: It is simple to send a configuration object to the Axios function to send an HTTP request. Using Axios, we may send a POST request to send data to a certain endpoint and start events. Call axios.post() to send an HTTP POST request using AXIOS. The URI of the service endpoint and an object containing the properties we want to send to the server are required when making a POST request in Axios. 

Syntax of POST Request of AXIOS:

axios.post(url[, data[, config]])

Also, we are using try and catch block for handling errors. We can specify a section of code to be tested for errors as it is being performed using the try statement. We can specify a block of code to be executed if an error occurs in the try block using the catch statement.

Try and Catch Syntax:

try {
    // Our Request Code
}
catch(err) {
    // Error Handling code
}

In try blocks, we have one payload object with some values and we want to post this payload object using a post request through Axios. We are using the Async function for making asynchronous requests and Await keyword for making requests in waiting for the state until the request returns some response. Once the request returns some response, we will store it in the result variable. If there is any error in a request that error will get handled in the catch() method. 

File: app.js

Javascript

const express = require("express");

const axios = require("axios");

const app = express();

const port = 8000;

app.get("/postRequest", async (req, res) => {

    try {

        payload = {

            name: "New Demo Airlines",

            country: "Demo",

            logo:

            slogan: "From Demo",

            headquarters: "State, Demo",

            website: "www.demo_website.com",

            established: "2000",

        };

        const result = await axios.post(

            payload

        );

        res.send(result.data);

    } catch (error) {

        if (error.response) {

            console.log("Data ", error.response.data);

            console.log("Status ", error.response.status);

            console.log("Headers ", error.response.headers);

        } else if (error.request) {

            console.log("called", error.request);

        } else {

            console.log("Error", error.message);

        }

        return res.status(401).send(error.message);

    }

});

app.listen(port, () => {

    console.log(`Example app listening on port ${port}`);

});

Output: In Output, First, we are successfully creating post requests using AXIOS. After creating a successful request, we are changing the valid URL to an Invalid URL which will create a 404(Not Found) error which gets handled by the first if-else condition. 
 

Approach 2: Using Then and Catch Method

Promise chains are excellent at handling errors. The then() method is invoked if a promise is successfully resolved. The control switches to the closest catch() error handler method when a promise rejects. No immediate action is required from the catch(). After one or possibly more then(), it might appear.

Syntax:

axios.get('/api-route-url')
    .then(result => {
        // Work here with the result
    }).catch(err => {
        // Error Handling here
        return res.status(401).send(err.message);
})

Here, In this implementation, We are using then and catch methods for handling responses and errors. If our request is successfully executed without any errors, then we will handle it in the then() method. If there is any error occurred in the request, then it will get handled in the catch() method. 

File: app.js

Javascript

const express = require("express");

const axios = require("axios");

const app = express();

const port = 8000;

app.get("/postRequest", (req, res) => {

    payload = {

        name: "GeeksforGeeks",

        country: "India",

        logo: 

        slogan: "From India, With Love",

        headquarters: "Delhi, India",

        website: "www.geeksforgeeks.org",

        established: "2000",

    };

    axios.post(

        payload

    ).then(result => {

        res.send(result.data);

    }).catch(error => {

        if (error.response) {

            console.log("Data", error.response.data);

            console.log("Status", error.response.status);

            console.log("Headers", error.response.headers);

        } else if (error.request) {

            console.log("<<<<<<<Response Not Received>>>>>>>>");

            console.log(error.request);

        } else {

            console.log("Error", error.message);

        }

        return res.status(401).send(error.message);

    });

});

app.listen(port, () => {

    console.log(`Example app listening on port ${port}`);

});

Output:

It should be noted that while both of these methods are capable of producing the same functionality, async/await is frequently preferred because it can handle longer promise chains easily.

Axios is a promise-based HTTP Client Javascript library for Node.js and Browser. In this tutorial, we will create examples that use Axios to make Get/Post/Put/Delete request. The final section shows a simple Axios HTTP Client to interact with Rest API.

Related Posts:
– Axios File Upload example
– Axios Interceptors tutorial with Refresh Token example
– Javascript Fetch API tutorial: Get/Post/Put/Delete example
– React Axios example – Get/Post/Put/Delete with Rest API
– React Query and Axios example with Rest API
– Vue Axios example – Get/Post/Put/Delete with Rest API

Contents

  • Axios Features
  • Install Axios
  • Axios Response Object schema
  • Axios Response Body
  • Axios Error handling
  • Axios Error handling with async-await
  • Axios GET request
  • Axios GET with params
  • Axios GET with headers
  • Axios GET with params and headers
  • Axios POST with body
  • Axios POST with headers
  • Axios PUT request
  • Axios PUT with headers
  • Axios DELETE request
  • Axios DELETE with headers
  • Create Axios instance
  • Axios Request example with Rest API
  • Source Code
  • Conclusion
  • Further Reading

Axios Features

Axios can run in the Node.js and Browser with the same codebase.
– On the server-side it uses the native Node.js http module
– On the client-side (browser) it uses XMLHttpRequests

Additionally, there are important features that you should know:

  • Supports the Promise API
  • Intercept request and response (Axios Interceptors tutorial)
  • Transform request and response data
  • Cancel requests
  • Automatic transforms for JSON data
  • Client side support for protecting against XSRF

(from https://github.com/axios/axios#features)

Install Axios

We can add Axios to our project/code with one of following simple ways:

– npm:

npm install axios

– bower:

bower install axios

– yarn:

yarn add axios

– CDN:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

Or:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Axios Response Object schema

The response for a Axios request contains:

  • data: parsed response body provided by the server
  • status: HTTP status code
  • statusText: HTTP status message
  • headers: HTTP headers (lower case)
  • config: the request config that was provided to axios
  • request: the last client request instance that generated this response

For example:

{
  "data": {
    "id": 1,
    "title": "Axios Request",
    "description": "Tut#1 Description",
    "published": true
  },
  "status": 200,
  "statusText": "OK",
  "headers": {
    "content-length": "162",
    "content-type": "application/json; charset=utf-8"
  },
  "config": {
    "url": "/tutorials/1",
    "method": "get",
    "headers": {
      "Accept": "application/json, text/plain, */*"
    },
    "baseURL": "http://localhost:8080/api",
    "transformRequest": [
      null
    ],
    "transformResponse": [
      null
    ],
    "timeout": 0,
    "xsrfCookieName": "XSRF-TOKEN",
    "xsrfHeaderName": "X-XSRF-TOKEN",
    "maxContentLength": -1,
    "maxBodyLength": -1
  }
}

Axios Response Body

Axios Response Object has data field that contains the parsed response body.
We can use then or await to receive the response body as follows:

axios.get('/bezkoder.com/tutorials')
  .then(function (response) {
    console.log(response.data);
  });

const { data } = await axios.get(url);

Axios Error handling

We use catch() for handling errors.

axios.get('/bezkoder.com/tutorials')
  .then(...)
  .catch(function (error) {
    if (error.response) { // get response with a status code not in range 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) { // no response
      console.log(error.request);
      // instance of XMLHttpRequest in the browser
      // instance ofhttp.ClientRequest in node.js
    } else { // Something wrong in setting up the request
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

Axios Error handling with async-await

If you want to use async-await, just wrap the axios call with try/catch block.

async function getTutorial() {
  try {
    const response = await axios.get('/bezkoder.com/tutorials');
    console.log(response);
  } catch (error) {
    if (error.response) { // get response with a status code not in range 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) { // no response
      console.log(error.request);
    } else { // Something wrong in setting up the request
      console.log('Error', error.message);
    }
    console.log(error.config);
  }
}
axios.get('/bezkoder.com/tutorials')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });

Async/await:

async function getTutorial() {
  try {
    const response = await axios.get('/bezkoder.com/tutorials');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

Axios GET with params

You can use the params config option to set query string params.

axios.get(
  '/bezkoder.com/tutorials',
  {
    params: {
      title: 'ios'
    }
  }
);

And this is equivalent:

axios.get('/tutorials?title=ios');

To send Axios GET request with Headers, we pass an option object with headers property.

axios.get(
  '/bezkoder.com/tutorials',
  {
    headers: {
      'x-access-token': 'token-value'
    }
  }
);

Axios GET with params and headers

We can merge params and headers in a Axios GET request like this.

axios.get(
  '/bezkoder.com/tutorials',
  {
    params: {
      title: 'ios'
    },
    headers: {
      'x-access-token': 'token-value'
    }
  }
);

Axios POST with body

You can perform an Axios POST object request with body as second parameter.

axios.post(
  '/bezkoder.com/tutorials',
  {
    title: title,
    description: description,
  }
);

To send Axios POST request with Headers, we pass an option object with headers property right after the body.

await axios.post(
  '/bezkoder.com/tutorials',
  {
    title: title,
    description: description,
  },
  {
    headers: {
      "x-access-token": "token-value",
    },
  }
);

Axios PUT request

You can perform an Axios PUT json object request with body as second parameter.

axios.put(
  '/bezkoder.com/tutorials/42',
  {
    title: title,
    description: description,
    published: true,
  }
);

To send Axios PUT request with Headers, we pass an option object with headers property right after the body.

axios.put(
  '/bezkoder.com/tutorials/42',
  {
    title: title,
    description: description,
    published: true,
  },
  {
    headers: {
      "x-access-token": "token-value",
    },
  }
);

Axios DELETE request

axios.delete('/bezkoder.com/tutorials/42');

To send Axios DELETE request with Headers, we pass an option object with headers property.

axios.delete(
  '/bezkoder.com/tutorials/42',
  {
    headers: {
      "x-access-token": "token-value",
    },
  }
);

Create Axios instance

We can create a new instance of axios using axios.create(config) method.

const instance = axios.create({
  baseURL: 'https://bezkoder.com/api/',
  timeout: 2000,
  headers: {'X-Custom-Header': 'bezkoder'}
});

Axios Request example with Rest API

We will build a HTTP Client to make CRUD requests to Rest API in that:

  • Axios GET request: get all Tutorials, get Tutorial by Id, find Tutorial by title
  • Axios POST request: create new Tutorial
  • Axios PUT request: update an existing Tutorial
  • Axios DELETE request: delete a Tutorial, delete all Tutorials

axios-request-example-get-post-put-delete

This Axios Client works with the following Web API:

Methods Urls Actions
POST /api/tutorials create new Tutorial
GET /api/tutorials retrieve all Tutorials
GET /api/tutorials/:id retrieve a Tutorial by :id
PUT /api/tutorials/:id update a Tutorial by :id
DELETE /api/tutorials/:id delete a Tutorial by :id
DELETE /api/tutorials delete all Tutorials
GET /api/tutorials?title=[keyword] find all Tutorials which title contains keyword

You can find step by step to build a Server like this in one of these posts:

  • Express, Sequelize & MySQL
  • Express, Sequelize & PostgreSQL
  • Express, Sequelize & SQL Server
  • Express & MongoDb
  • Spring Boot & MySQL
  • Spring Boot & PostgreSQL
  • Spring Boot & MongoDB
  • Spring Boot & SQL Server
  • Spring Boot & H2
  • Spring Boot & Cassandra
  • Spring Boot & Oracle
  • Django & MySQL
  • Django & PostgreSQL
  • Django & MongoDB

Remember that you need to configure CORS: Access-Control-Allow-Origin: *.
It helps the REST APIs can be accessed by any origin.

– Create a Tutorial using axios POST request:

axios-post-request-example

– Retrieve all Tutorials using axios GET request:

axios-get-request-example

– Retrieve a Tutorial by Id using axios GET request:

axios-get-request-example-by-id

– Find Tutorials by title using axios GET request with params:

axios-get-request-params-example

– Update a Tutorial using axios PUT request:

axios-put-request-example

– Delete Tutorial using axios DELETE request:

axios-delete-request-example

Source Code

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Axios Requests example</title>
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
    />
  </head>
  <body>
    <div class="container my-3" style="max-width: 600px">
      <h3>Axios Requests example</h3>

      <div class="card mt-3">
        <div class="card-header">Axios GET Request - BezKoder.com</div>
        <div class="card-body">
          <div class="input-group input-group-sm">
            <button class="btn btn-sm btn-primary" onclick="getAllData()">Get All</button>

            <input type="text" id="get-id" class="form-control ml-2" placeholder="Id">
            <div class="input-group-append">
              <button class="btn btn-sm btn-primary" onclick="getDataById()">Get by Id</button>
            </div>

            <input type="text" id="get-title" class="form-control ml-2" placeholder="Title">
            <div class="input-group-append">
              <button class="btn btn-sm btn-primary" onclick="getDataByTitle()">Find By Title</button>
            </div>

            <button class="btn btn-sm btn-warning ml-2" onclick="clearGetOutput()">Clear</button>
          </div>   
          
          <div id="getResult"></div>
        </div>
      </div>

      <div class="card mt-3">
        <div class="card-header">Axios POST Request - BezKoder.com</div>
        <div class="card-body">
          <div class="form-group">
            <input type="text" class="form-control" id="post-title" placeholder="Title">
          </div>
          <div class="form-group">
            <input type="text" class="form-control" id="post-description" placeholder="Description">
          </div>
          <button class="btn btn-sm btn-primary" onclick="postData()">Post Data</button>
          <button class="btn btn-sm btn-warning" onclick="clearPostOutput()">Clear</button>

          <div id="postResult"></div>
        </div>
      </div>

      <div class="card mt-3">
        <div class="card-header">Axios PUT Request - BezKoder.com</div>
        <div class="card-body">
          <div class="form-group">
            <input type="text" class="form-control" id="put-id" placeholder="Id">
          </div>
          <div class="form-group">
            <input type="text" class="form-control" id="put-title" placeholder="Title">
          </div>
          <div class="form-group">
            <input type="text" class="form-control" id="put-description" placeholder="Description">
          </div>
          <div class="form-check">
            <input type="checkbox" class="form-check-input" id="put-published">
            <label class="form-check-label" for="put-published">Publish</label>
          </div>
          <div class="form-group mt-2">
            <button class="btn btn-sm btn-primary" onclick="putData()">Update Data</button>
            <button class="btn btn-sm btn-warning" onclick="clearPutOutput()">Clear</button>
          </div>

          <div id="putResult"></div>
        </div>
      </div>

      <div class="card mt-3">
        <div class="card-header">Axios DELETE Request - BezKoder.com</div>
        <div class="card-body">
          <div class="input-group input-group-sm">
            <button class="btn btn-sm btn-danger" onclick="deleteAllData()">Delete All</button>

            <input type="text" id="delete-id" class="form-control ml-2" placeholder="Id">
            <div class="input-group-append">
              <button class="btn btn-sm btn-danger" onclick="deleteDataById()">Delete by Id</button>
            </div>

            <button class="btn btn-sm btn-warning ml-2" onclick="clearDeleteOutput()">Clear</button>
          </div>    
          
          <div id="deleteResult"></div>      
        </div>
      </div>
    </div>

    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    <script src="main.js"></script>
  </body>
</html>

main.js

const instance = axios.create({
  baseURL: "http://localhost:8080/api",
  headers: {
    "Content-Type": "application/json",
  },
});

function htmlizeResponse(res) {
  return `<div class="alert alert-secondary mt-2" role="alert"><pre>` + JSON.stringify(res, null, 2) + "</pre></div>";
}

async function getAllData() {
  let resultElement = document.getElementById("getResult");
  resultElement.innerHTML = "";

  try {
    const res = await instance.get("/tutorials");

    const result = {
      status: res.status + "-" + res.statusText,
      headers: res.headers,
      data: res.data,
    };

    resultElement.innerHTML = htmlizeResponse(result);
  } catch (err) {
    resultElement.innerHTML = htmlizeResponse(err);
  }
}

async function getDataById() {
  let resultElement = document.getElementById("getResult");
  resultElement.innerHTML = "";

  const id = document.getElementById("get-id").value;

  if (id) {
    try {
      const res = await instance.get(`/tutorials/${id}`);

      const result = {
        status: res.status + "-" + res.statusText,
        headers: res.headers,
        data: res.data,
      };

      resultElement.innerHTML = htmlizeResponse(result);
    } catch (err) {
      resultElement.innerHTML = htmlizeResponse(err);
    }
  }
}

async function getDataByTitle() {
  let resultElement = document.getElementById("getResult");
  resultElement.innerHTML = "";

  const title = document.getElementById("get-title").value;

  if (title) {
    try {
      // const res = await instance.get(`/tutorials?title=${title}`);
      const res = await instance.get("/tutorials", {
        params: {
          title: title
        }
      });

      const result = {
        status: res.status + "-" + res.statusText,
        headers: res.headers,
        data: res.data,
      };

      resultElement.innerHTML = htmlizeResponse(result);
    } catch (err) {
      resultElement.innerHTML = htmlizeResponse(err);
    }
  }
}

async function postData() {
  let resultElement = document.getElementById("postResult");
  resultElement.innerHTML = "";

  const title = document.getElementById("post-title").value;
  const description = document.getElementById("post-description").value;

  try {
    const res = await instance.post("/tutorials", {
      title: title,
      description: description,
    });

    const result = {
      status: res.status + "-" + res.statusText,
      headers: res.headers,
      data: res.data,
    };

    resultElement.innerHTML = htmlizeResponse(result);
  } catch (err) {
    resultElement.innerHTML = htmlizeResponse(err);
  }
}

async function putData() {
  let resultElement = document.getElementById("putResult");
  resultElement.innerHTML = "";

  const id = document.getElementById("put-id").value;
  const title = document.getElementById("put-title").value;
  const description = document.getElementById("put-description").value;
  const published = document.getElementById("put-published").checked;

  try {
    const res = await instance.put(`/tutorials/${id}`, {
      title: title,
      description: description,
      published: published
    });

    const result = {
      status: res.status + "-" + res.statusText,
      headers: res.headers,
      data: res.data,
    };

    resultElement.innerHTML = htmlizeResponse(result);
  } catch (err) {
    resultElement.innerHTML = htmlizeResponse(err);
  }
}

async function deleteAllData() {
  let resultElement = document.getElementById("deleteResult");
  resultElement.innerHTML = "";

  try {
    const res = await instance.delete("/tutorials");

    const result = {
      status: res.status + "-" + res.statusText,
      headers: res.headers,
      data: res.data,
    };

    resultElement.innerHTML = htmlizeResponse(result);
  } catch (err) {
    resultElement.innerHTML = htmlizeResponse(err);
  }
}

async function deleteDataById() {
  let resultElement = document.getElementById("deleteResult");
  resultElement.innerHTML = "";

  const id = document.getElementById("delete-id").value;

  try {
    const res = await instance.delete(`/tutorials/${id}`);

    const result = {
      status: res.status + "-" + res.statusText,
      headers: res.headers,
      data: res.data,
    };

    resultElement.innerHTML = htmlizeResponse(result);
  } catch (err) {
    resultElement.innerHTML = htmlizeResponse(err);
  }
}

function clearGetOutput() {
  document.getElementById("getResult").innerHTML = "";
}

function clearPostOutput() {
  document.getElementById("postResult").innerHTML = "";
}

function clearPutOutput() {
  document.getElementById("putResult").innerHTML = "";
}

function clearDeleteOutput() {
  document.getElementById("deleteResult").innerHTML = "";
}

Conclusion

With this Axios tutorial, you’ve known many ways to make GET/POST/PUT/DELETE request using Axios (with headers, params, body…). You can also use it in:
– React App: React Axios example – Get/Post/Put/Delete with Rest API
Or: React Query and Axios example with Rest API

– Vue App: Vue Axios example – Get/Post/Put/Delete with Rest API

Furthermore, you can apply it in one of following React/Vue CRUD applications:

  • React CRUD example with Axios & React Router
  • React Redux CRUD example with Axios & React Router
  • Vue 2 CRUD Application with Axios & Vue Router
  • Vue 3 CRUD example with Axios & Vue Router

If you want to use Fetch API instead, please visit:
Javascript Fetch API tutorial: Get/ Post/ Put/ Delete example

Happy Learning! See you again.

Further Reading

  • https://github.com/axios/axios
  • Axios File Upload example
  • Axios Interceptors tutorial with Refresh Token example

Grepper Logo

Add Answer
|
View In TPC Matrix

Technical Problem Cluster First Answered On
February 15, 2021

Popularity
10/10

Helpfulness
7/10


Contributions From The Grepper Developer Community

Contents

Code Examples

  • axios get error message
  • Related Problems

  • how to get error message axios
  • axios get message from error
  • error.message axios
  • axios error
  • axios get error response body
  • axios network error
  • axios error handling function
  • best status codes to handle in axios eror
  • axios error handle npm
  • axios try catch
  • try catch javascript axios
  • axios try catch get error status cocxe
  • axios authorization error
  • axios post code
  • TPC Matrix View Full Screen

    axios get error message

    Comment

    4


    Popularity

    10/10 Helpfulness
    7/10
    Language
    javascript

    Source: Grepper

    Tags: axios
    get
    javascript
    message

    Sbeajy

    Contributed on Feb 15 2021

    Sbeajy

    4 Answers  Avg Quality 8/10


    Grepper

    Features
    Reviews
    Code Answers
    Search Code Snippets

    Plans & Pricing
    FAQ
    Welcome
    Browsers Supported
    Grepper Teams

    Documentation

    Adding a Code Snippet

    Viewing & Copying Snippets

    Social

    Twitter LogoTwitter

    LinkedIn LogoLinkedIn

    Legal

    Privacy Policy
    Terms

    Contact

    support@codegrepper.com

    Jul 23, 2020

    When you await on an Axios request, you get back an Axios response. An Axios response is a POJO with several
    properties, including data, which contains the parsed response body.

    const axios = require('axios');
    
    const res = await axios.get('https://httpbin.org/get', { params: { answer: 42 } });
    
    res.constructor.name; // 'Object', means `res` is a POJO
    
    // `res.data` contains the parsed response body
    res.data; // { args: { answer: 42 }, ... }
    res.data instanceof Object; // true

    An Axios response contains several other properties, like status, which contains the HTTP response status
    code (like 200 or 404). But most of the time you don’t care about the response code if the request
    succeeded, so you will often see code that gets the response body directly using promise chaining.

    const data = await axios.get(url).then(res => res.data);

    You can also get the response body using destructuring assignments.

    // Equivalent to `const data = await axios.get(url).then(res => res.data)`
    const { data } = await axios.get(url);

    Automatic Parsing

    Axios parses the response based on the HTTP response’s Content-Type header. When the response’s content type
    is application/json, Axios will automatically try to parse the response into a JavaScript object.

    const axios = require('axios');
    
    const res = await axios.get('https://httpbin.org/get', { params: { answer: 42 } });
    
    res.headers['content-type']; // 'application/json'

    Keep in mind that the response headers are sent by the server. So if the server sends back a different content
    type, you may need to handle it the response yourself.

    For other content types, like text/html, the res.data property will be a string.

    const axios = require('axios');
    
    const res = await axios.get('https://httpbin.org/html');
    
    res.headers['content-type']; // 'text/html; charset=utf-8'
    
    typeof res.data; // 'string'
    res.data; // '... <h1>Herman Melville - Moby-Dick</h1> ...'

    Streaming

    You can configure the type of the data property using Axios’ responseType object. By default,
    responseType is set to 'json', which means Axios will try to parse the response as JSON.

    However, that isn’t correct if you’re looking to, say, download an image using Axios. You can set responseType to 'arraybuffer' to get the response as an ArrayBuffer:

    const axios = require('axios');
    
    const res = await axios.get('https://images.unsplash.com/photo-1506812574058-fc75fa93fead', {
      responseType: 'arraybuffer'
    });
    
    const fs = require('fs');
    fs.writeFileSync('./south-beach.jpg', res.data);

    You can also set responseType to 'stream' to get the response as a Node.js stream:

    const axios = require('axios');
    
    const res = await axios.get('https://images.unsplash.com/photo-1506812574058-fc75fa93fead', {
      responseType: 'stream'
    });
    
    const fs = require('fs');
    res.data.pipe(fs.createWriteStream('./south-beach.jpg'));

    React

    Когда вы делаете вызов к бэкенд API с axios, вы должны рассмотреть, что делать с блоком .catch() вашего промиса. Теперь вам может показаться, что ваш API высокодоступен и он будет работать 24/7, что рабочий процесс пользователя довольно ясен, ваш JavaScript вменяем и у вас есть модульные тесты. Поэтому, когда вы смотрите на блок catch при выполнении запросов с помощью axios, вы можете подумать: “Ну… Я просто использую console.log. Все будет в порядке.”

    Skillfactory.ru

    axios.get('/my-highly-available-api')
      .then(response => { 
        // do stuff 
      }) 
      .catch(err => { 
        // what now? 
        console.log(err); 
      })

    Но есть еще так много вещей, которые находятся вне вашего контроля, которые могут вызвать ошибки при выполнении запросов API — и вы, вероятно, даже не знаете, что они происходят!

    Эта статья посвящена в основном ошибкам, которые вы видите в браузере. На бэкенде тоже все может выглядеть довольно забавно. Просто взгляните на три вещи, которые вы можете увидеть в своих бэкенд журналах.

    Ниже приведены три типа ошибок, которые могут появиться, и как их обрабатывать при использовании axios.

    Отлов ошибок Axios

    Ниже приведен фрагмент кода, который я начал включать в несколько проектов JS:

    axios.post(url, data)
      .then(res => { 
        // do good things 
      }) 
      .catch(err => { 
        if (err.response) { 
          // client received an error response (5xx, 4xx)
        } else if (err.request) { 
          // client never received a response, or request never left 
        } else { 
          // anything else 
        } 
      })

    Каждое условие предназначено для фиксации различного типа ошибки.

    Проверка error.response

    Если ваш объект error содержит поле response, это означает, что сервер ответил с ошибкой 4xx/5xx. Обычно это та ошибка, с которой мы лучше всего знакомы и с которой легче всего справиться.

    Применяйте следующее: “Показать страницу 404 Not Found / сообщение об ошибке, если ваш API возвращает 404.” Покажите другое сообщение об ошибке, если ваш бэкенд возвращает 5xx или вообще ничего не возвращает. Вы может показаться, что ваш хорошо сконструированный бэкенд не будет генерировать ошибки, но это всего лишь вопрос времени, а не “если”.

    Проверка error.request

    Второй класс ошибок — это когда у вас нет ответа, но есть поле request, прикрепленное к ошибке. Когда же это происходит? Это происходит, когда браузер смог сделать запрос, но по какой-то причине не получил ответа. Это может произойти, если:

    • Вы находитесь в обрывочной сети (например, в метро или используете беспроводную сеть здания).

    • Ваш бэкенд зависает на каждом запросе и не возвращает ответ вовремя.

    • Вы делаете междоменные запросы, но вы не авторизованы, чтобы их делать.

    • Вы делаете междоменные запросы, и вы авторизованы, но бэкенд API возвращает ошибку.

    Skillfactory.ru

    Одна из наиболее распространенных версий этой ошибки имела бесполезное сообщение “Ошибка сети”. У нас есть API для фронтенда и бэкенда, размещенные в разных доменах, поэтому каждый вызов к бэкенд API — это междоменный запрос.

    Из-за ограничений безопасности на JS в браузере, если вы делаете запрос API, и он не работает из-за плохих сетей, единственная ошибка, которую вы увидите — это “Ошибка сети”, которая невероятно бесполезна. Она может означать что угодно: от “Ваше устройство не имеет подключения к Интернету” до “Ваши OPTIONS вернули 5xx” (если вы делаете запросы CORS). Причина ошибки сети хорошо описана в этом ответе на StackOverflow.

    Все остальные типы ошибок

    Если ваш объект error не содержит поля response или request, это означает, что это не ошибка axios и, скорее всего, в вашем приложении что-то еще не так. Сообщение об ошибке + трассировка стека должны помочь вам понять, откуда оно исходит.

    Как вам их исправить?

    Ухудшение пользовательского опыта

    Все это зависит от вашего приложения. Для проектов, над которыми я работаю, для каждой функции, использующей эти конечные точки, мы ухудшаем пользовательский опыт.

    Например, если запрос не выполняется и страница бесполезна без этих данных, то у нас будет большая страница ошибок, которая появится и предложит пользователям выход — иногда это всего лишь кнопка “Обновить страницу”.

    Другой пример: если запрос на изображение профиля в потоке социальных сетей не выполняется, мы можем показать изображение-плейсхолдер и отключить изменения изображения профиля вместе с всплывающим уведомлением, объясняющим, почему кнопка “Обновить изображение профиля” отключена. Однако показывать предупреждение с надписью “422 необработанных объекта” бесполезно для пользователя.

    Обрывистые сети

    Веб-клиент, над которым я работаю, используется в школьных сетях, которые бывают совершенно ужасны. Доступность бэкенда едва ли имеет к этому какое-то отношение. Запрос иногда не выходит из школьной сети.

    Для решения такого рода периодических проблем с сетью, мы добавили axios-retry, что решило большое количество ошибок, которые мы наблюдали в продакшне. Это было добавлено в нашу настройку axios:

    const _axios = require('axios') 
    const axiosRetry = require('axios-retry') 
    const axios = _axios.create() 
    // https://github.com/softonic/axios-retry/issues/87 const retryDelay = (retryNumber = 0) => { 
      const seconds = Math.pow(2, retryNumber) * 1000; 
      const randomMs = 1000 * Math.random(); 
      return seconds + randomMs; 
    }; 
    axiosRetry(axios, { 
      retries: 2, 
      retryDelay, 
      // retry on Network Error & 5xx responses 
      retryCondition: axiosRetry.isRetryableError, 
    }); 
    module.exports = axios;

    Мы увидели, что 10% наших пользователей (которые находятся в плохих школьных сетях) периодически наблюдали ошибки сети, но число снизилось до <2% после добавления автоматических повторных попыток при сбое.

    Скриншот количества ошибок сети, как они появляются в браузере New Relic. <1% запросов неверны. Это подводит меня к последнему пункту.

    Добавляйте отчеты об ошибках в свой интерфейс

    Полезно иметь отчеты об ошибках и событиях фронтенда, чтобы вы знали, что происходит в разработке, прежде чем ваши пользователи сообщат вам о них. На моей основной работе мы используем браузер New Relic для отправки событий ошибок с фронтенда. Поэтому всякий раз, когда мы ловим исключение, мы регистрируем сообщение об ошибке вместе с трассировкой стека (хотя это иногда бесполезно с минимизированными пакетами) и некоторыми метаданными о текущем сеансе, чтобы попытаться воссоздать его.

    Другие инструменты, используемые нами— Sentry + SDK браузер, Rollbar и целая куча других полезных инструментов, перечисленных на GitHub.

    Заключение

    Если вы больше ничего не можете выжать из этого, сделайте одно: перейдите в свою кодовую базу и просмотрите, как вы обрабатываете ошибки с помощью axios.

    • Проверьте, выполняете ли вы автоматические повторы, и, если нет, добавьте axios-retry.
    • Проверьте, что вы отлавливаете ошибки и сообщаете пользователю, что что-то произошло. Использовать только axios.get(...).catch(console.log) недостаточно.

    Читайте также:

    • React TypeScript: Основы и лучшие практики
    • Первые шаги в анимации React Native
    • Как предотвратить состояние гонки с помощью React Context API

    Перевод статьи Danny Perez: How to Handle API Errors in Your Web App Using Axios

    Понравилась статья? Поделить с друзьями:
  • Axios error config
  • Axios create error
  • Axios catch error typescript
  • Axios catch error 400
  • Axios 422 error