Axios Nodejs

Learn via video courses
Topics Covered

Overview

Axios is an HTTP library for Promise-based asynchronous requests. Its API is easy to use and can be used in many different environments, including NodeJS (server-side) and the browser (client-side). Axios is used to make REST API calls to perform desired operations on the back end and fetch data to the front end. It also comes with built-in error-handling features which help with code debugging. The API works well with popular front-end libraries like React and 'Angular', making it the first choice for a lot of developers.

What is Axios?

Axios is one of the most popular JavaScript libraries in the world. It is an HTTP client that can be used to make requests from both browsers and NodeJS. It supports the Promise API natively since making requests is an asynchronous process. Axios is known for its ease of use compared to the JavaScript native fetch method.

Axios can be used to fetch data from and to your favorite front-end library like React or Vue. Working with APIs like REST APIs to perform operations like Create, Read, Update, and Delete on the database becomes much easier with Axios in Node.js. Axios also offers other useful features to work with API and requests.

What is Axios

Why Use Axios NPM Package?

  • Axios is easier to use than the native fetch method as methods are much more well-defined. Eg. the get() method in Axios tells us that we are making a GET request and there is no need to specifically request methods explicitly.
  • Axios requires fewer lines of code since it has in-built JSON support and parsing. JSON response is automatically transformed to a JavaScript object while in the fetch method, one would need to use response.json() to manually transform it. To use the response data in the application, it is mandatory to transform JSON data into a JavaScript object.
  • We can send HTTP requests from a Node.js backend and XHR - XMLHTTPRequests from the browser.
  • Axios provides a better experience when it comes to error handling. It has clear error messages and error codes. This makes debugging applications with Axios easier.
  • A response timeout can be easily set up with Axios as it can be simply added as property timeout = 5000 in the config object. If we were to implement this functionality using the fetch method then we would need to use the AbortController interface which requires manual initialization and calling. This increases the number of lines of code and complexity whereas, in Axios, it is just a single line.

Features

  • Compact Library for easy HTTP communication
  • Axios is a Promise-based Library
  • It can be used to make HTTP requests from Node.js and XHR requests from the browser
  • Out of the box JSON parsing
  • Extensive error handling with error messages and error codes.
  • We can easily abort requests, cancel requests, and also set request timeouts.
  • In-built security against session riding.
  • Backwards compatibility. Axios even supports Internet Explorer!

Browser Support

As per the official documentation of Axios, the following browsers are supported according to their versions. Using browsers not mentioned below for Axios, may not work as intended.

BrowserVersionSupported ( Yes / No)
Google ChromeLatestYes
FirefoxLatestYes
OperaLatestYes
SafariLatestYes
Microsoft EdgeLatestYes
Internet Explorer11Yes

How to Install Axios Using NPM Package?

To install Axios using `Node Package Manager, run the following command in your NodeJS project:

npm install axios

Install Axios Using NPM Package

We can also use a Content Delivery Network link to use CDN on our HTML page:

Getting Started with Axios

In this section, we will learn how to send various HTTP requests using Axios in Node.js. We will be making REST API calls to an e-commerce back-end application for the following operations:

  • GET - To get all the products in one category, eg: all mobiles
  • POST - To create a new product in the database
  • PUT - To modify an existing product data
  • DELETE - To delete an existing product

Make HTTP Requests - Get Request

To make a get request to a backend, we will use the following snippet:

The above code makes a get request to a local backend server and logs the status code and response data to the console.

Here is the output: ( only displaying a few from a long list of products )

Getting Started with Axios

The status code is 200 which means successful fetching of data. The response data is an object. This is a JSON object parsed into a JS object and has a data key with an array of product objects.

Make HTTP Requests - Post Request

Here is the snippet for sending a POST request to the back end:

Here is the response that we receive: Getting Started with Axios-2

Make HTTP Requests - Delete Request

Let's try deleting one of the products now. Here is the snippet for deleting. Note that we have switched the syntax a bit to show async-await functionality:

Here we are deleting the product with id = 3.

Here is the output in the console:

Getting Started with Axios-3

Make HTTP Requests - Put Request

Finally, we will try to update the existing data in the database in the back end. Here is the snippet for the same:

Here we update the product with id = 1 with the data in the object. Here is the output in the console:

Getting Started with Axios-4

Thus, we have successfully used Axios to make all major REST API calls i.e. GET, POST, DELETE and PUT requests in Node.js.

Axios API

In this section, we will learn how to make explicit configurations using Axios in Node.js.

We can make a config object and pass that object to the Axios method. Here is the snippet for this:

Here is the response to this request:

Axios API-1

There are also default methods for ease of use. For example, for a GET Request to an activity suggesting API, we can simply use the following code:

Notice how there is no need to even mention the get method. Here is the response data in the console: Axios API-2

Beyond JavaScript Basics: Our Full Stack Web Developer Course Guides You Through Advanced Techniques. Enroll Now & Transform Your Coding Expertise.

Axios Response Object Schema

Up until now, we have only seen the data object but we also receive other properties in the Response Object. Let's take a look at the response object as a whole:

To get the full response use the following snippet:

The response to the request:

Here is a small response object. We can see various properties like:

  • Status: The status code for the request along with the status Text.
  • Headers: Headers include extra information about the request.
  • Config: The configuration data of the request.
  • URL: Base URL to which the request was made.
  • Method: The Request method like Get, Post, Patch, Delete, etc.
  • Data: The data object is the actual API data.

Axios Response Body

If we only want the response data then we do a small modification to our code :

The data for the request:

Axios Response Body

Axios Error Handling

We can use the catch block to handle errors. Axios provides us with an error object to better handle errors. Let's try requesting to get data of a user without the credentials. Here is the snippet:

This API call will throw an error because we don't have the authorization to access the data of the user with userId = 5 as per the GET request. Here is the error in the console:

Axios Error Handling

We have logged the Error Status Code, The error message, and the error data object. This lets the user know that they are trying to access an Unauthorized resource and hence they are getting the error.

Axios Error Handling with Async-Await

Since Axios is Promise-based, we can use Async-Await as well. Here we will try to handle the errors using async-await functionality.

Here is the response in the console:

Axios Error Handling with Async-Await-2

Similarly, the Async-Await syntax can be used for all CRUD - Create, Read, Update Delete requests as well. We can send GET, PUT, POST, and DELETE requests using async-await with Axios in Node.js.

How to Remove Axios Package?

To uninstall Axios from the application, simply run the following command:

npm uninstall axios

This will uninstall Axios dependency. Remove Axios Package

Node.js is the backbone of modern web applications. Enroll in our free Node JS course and learn to create efficient, real-time applications.

Conclusion

  • Axios is a library used to make HTTP requests from Node.js and XHR requests from the browser.
  • We can easily make calls to REST APIs and perform CRUD operations using inbuilt methods.
  • It automatically parses JSON and converts JSON objects to JavaScript objects.
  • Axios comes with out-of-the-box error handling capabilities and makes debugging easier.
  • Axios can also be used to setrequest-timeouts and abort or cancel requests.
  • It is much easier to use than the native fetch method.
  • Since Axios is based on promises, it can be used with both .then() syntax and async-await syntax.
  • Axios has easy integration with applications and it is used with popular frameworks and libraries like React and Angular