Home > Web Front-end > JS Tutorial > Axios Beginner's Guide: A Handy Promise-based HTTP Client

Axios Beginner's Guide: A Handy Promise-based HTTP Client

Jennifer Aniston
Release: 2025-02-15 09:06:13
Original
494 people have browsed it

Axios Beginner's Guide: A Handy Promise-based HTTP Client

Key Points of Axios

  • Axios is a popular Promise-based HTTP client with an easy-to-use API that can be used in browsers and Node.js environments. It provides a versatile tool for JavaScript developers.
  • Axios differs from the built-in Fetch API in several ways, including its handling of HTTP error codes, the automatic inclusion of cookies in requests, and the ability to provide upload/download progress updates.
  • Axios allows developers to convert output or input data and add interceptors, functions that are triggered when a request is made or a response is received. These features provide flexibility for processing data and managing requests and responses.
  • A powerful third-party library ecosystem exists to extend the capabilities of Axios. These add-ons cover from interceptors and test adapters to loggers, enhancing Axios' capabilities in different use cases.

Axios is a popular Promise-based HTTP client with an easy-to-use API and can be used in browsers and Node.js environments. Making HTTP requests to get or save data is one of the most common tasks for client JavaScript applications. Third-party libraries (especially jQuery) have long been a popular way to interact with lengthy browser APIs and eliminate cross-browser differences. As people gradually abandon jQuery and turn to improved native DOM APIs or front-end UI libraries such as React and Vue.js, it becomes meaningless to include it just for its $.ajax functionality. Let's see how to get started with Axios in your code and learn about some features that make it popular among JavaScript developers.

Comparison of Axios vs. Fetch

You may already know that modern browsers have newer Fetch API built in, so why not just use it? There are some differences between the two, which many believe makes Axios more advantageous. One of the differences is how these two libraries handle HTTP error codes. When using Fetch, if the server returns a 4xx or 5xx series error, your catch() callback will not be triggered and the developer needs to check the response status code to determine if the request is successful. On the other hand, if one of these status codes is returned, Axios will reject the request for the Promise. Another small difference that often confuses developers who are new to APIs is that Fetch does not automatically send cookies back to the server when making a request. An option must be passed explicitly to include them. Axios is here to support you. For some, one difference that can end up being a barrier is the progress update of upload/download. Since Axios is built on top of older XHR APIs, you can register onUploadProgress and onDownloadProgress callback functions to display the percentage of completion in the application's UI. Currently, Fetch does not support this feature. Finally, Axios is available in browsers and Node.js. This helps to share JavaScript code between the browser and the backend, or perform server-side rendering of the front-end application. Note: Node has a version of the Fetch API available, but in my opinion, the other features Axios offers make it more advantageous.

Installation

As you might expect, the most common way to install Axios is through the npm package manager:

npm i axios
Copy after login
Copy after login
Copy after login

and include it in your code where you need it:

// ES2015 风格导入
import axios from 'axios';

// Node.js 风格 require
const axios = require('axios');
Copy after login
Copy after login
Copy after login

If you are not using some kind of module bundler (such as webpack), you can always extract libraries from CDN in the traditional way:

<🎜>
Copy after login
Copy after login

Browser support

Axios runs in all modern web browsers and Internet Explorer 8.

Send a request

Similar to jQuery's $.ajax function, you can make any type of HTTP request by passing an option object to Axios:

axios({
  method: 'post',
  url: '/login',
  data: {
    user: 'brunos',
    lastName: 'ilovenodejs'
  }
});
Copy after login

Here, we tell Axios which HTTP method we want to use (such as GET/POST/DELETE etc.) and which URL should we make the request to. We also provide some data that will be sent with the request in the form of a simple key/value pair JavaScript object. By default, Axios will serialize it to JSON and send it as the request body.

Request Options

When you make a request, you can pass many other options, but here are some of the most common options:

  • baseUrl: If you specify a base URL, it will be attached to any relative URL you use.
  • headers: The key/value pair object to be sent as a header.
  • params: The key/value pair object that will be serialized and appended as a query string to the URL.
  • responseType: If the response format you expect is not JSON, you can set this property to arraybuffer, blob, document, text, stream, or
  • .
  • auth
  • : The object passing a username and password field will use these credentials to perform HTTP basic authentication on the request.

Convenient method

get Like jQuery, there are some shortcuts to perform different types of requests. The delete, head, options, and

methods all accept two parameters: a URL and an optional configuration object.
npm i axios
Copy after login
Copy after login
Copy after login

The postput, patch and

methods take the data object as their second parameter and the optional configuration object as their third parameter:
// ES2015 风格导入
import axios from 'axios';

// Node.js 风格 require
const axios = require('axios');
Copy after login
Copy after login
Copy after login

Receive response

After a request is made, Axios returns a Promise that will resolve to a response object or an error object.
<🎜>
Copy after login
Copy after login

Response object

then()If the request is successful, your

callback will receive a response object with the following properties:
  • data
  • : Payload returned by the server. By default, Axios expects JSON and parses it back into a JavaScript object.
  • status
  • : HTTP code returned by the server.
  • statusText
  • : HTTP status message returned by the server.
  • headers
  • : All headers sent back by the server.
  • config
  • : Original request configuration.
  • request
  • : (When running in the browser) The actual XMLHttpRequest object.

Error object

If there is a problem with the request, the Promise will be denied and an error object is displayed, which contains at least the following properties:
  • message
  • : Error message text.
  • response
  • : The response object described in the previous section (if received).
  • request
  • : (When running in the browser) The actual XMLHttpRequest object.
  • config
  • : Original request configuration.

Convert and Interceptor

$httpAxios provides some simplistic features inspired by Angular's

library. Although they look similar, their use cases are slightly different.

Convert

Axios allows you to provide functions to convert output or input data in the form of two configuration options you can set when making a request: transformRequest and transformResponse. Both properties are arrays that allow you to link multiple functions that will pass data. Any function passed to transformRequest will be applied to PUT, POST, and PATCH requests. They receive request data and header objects as parameters and must return the modified data object.

npm i axios
Copy after login
Copy after login
Copy after login

can add functions to transformResponse in the same way, but only call them before using response data and passing the response to any linked then() callback. So what can we use the conversion for? A potential use case is to deal with APIs that expect to receive data in a specific format, such as XML or even CSV. You can set up a pair of conversions to convert the output and input data into the format required by the API and convert it back from that format. It is worth noting that Axios' default transformRequest and transformResponse functions convert data to and from JSON, and specifying that your own will override those transformations.

Interceptor

While the conversion allows you to modify output and input data, Axios also allows you to add functions called interceptors. Like the conversion, these functions can also be attached to the request or fired when a response is received.

// ES2015 风格导入
import axios from 'axios';

// Node.js 风格 require
const axios = require('axios');
Copy after login
Copy after login
Copy after login

As you may have noticed from the example above, there are some important differences between interceptors and conversions. Instead of just receiving data or headers, an interceptor receives a complete request configuration or response object. When creating an interceptor, you can also choose to provide an error handler function that allows you to catch any errors and handle them appropriately. A request interceptor can be used to perform operations such as retrieving a token from a local store and sending it with all requests, while a response interceptor can be used to capture a 401 response and redirect it to a login page for authorization.

Third-party add-ons

As a popular library, Axios benefits from a third-party library ecosystem that extends its capabilities. From interceptors to test adapters to loggers, there are a lot of tools available. Here are some tools that I think you might find useful:

  • mock-adapter: Allows you to easily simulate requests to facilitate testing code.
  • cache-plugin: A wrapper for selectively cache GET requests.
  • redux-axios-middleware: If you are a Redux user, this middleware provides a clean way to schedule Ajax requests using normal old operations.

A list of more add-ons and extensions is available in the Axios GitHub repository. All in all, there are a lot to recommend at Axios. It has a simple API, and a practical and quick way that is familiar to anyone who has used jQuery before. Its popularity and the availability of various third-party add-ons make it a reliable option to include in your application, whether it’s on the front end, back end or both.

Axios FAQ (FAQ)

What is the difference between Axios and Fetch API?

Axios and Fetch APIs are both popular HTTP request tools. However, there are some key differences between the two. Axios is a Promise-based HTTP client that works in browsers and node.js environments. It provides a single API for handling HTTP interfaces for XMLHttpRequests and nodes. On the other hand, the Fetch API provides a common definition of Request and Response objects, which is also based on Promise. But unlike Axios, the Fetch API is not based on XMLHttpRequest, it is a built-in module for JavaScript ES6.

How to use Axios to handle errors?

Axios provides a powerful method of handling errors. When an error occurs during an Axios request, it is rejected and an error object is displayed. The error object contains information about the cause of the error, such as error messages, HTTP status codes, and request and response objects. You can catch this error using the try/catch block or the catch method of the Promise.

Can I use Axios in React?

Yes, Axios is available for React. In fact, it is a popular choice for making HTTP requests in React applications. You can use Axios in React to get data from the API and display it in your component. Axios requests in React can be made in the componentDidMount or useEffect hook.

How to cancel a request in Axios?

Axios provides a mechanism to cancel requests. This can be done using the CancelToken.source factory method. When you want to cancel the request, just call the cancel method on the source object.

How to make a POST request using Axios?

It is easy to make a POST request using Axios. You can use the post method of the Axios instance and pass the URL and data as parameters. The data should be a JavaScript object representing the requested payload.

Can I use Axios in Vue.js?

Yes, Axios is available for Vue.js. It is a popular choice for making HTTP requests in Vue.js applications. You can use Axios in Vue.js to get data from the API and display it in your component.

How to set default headers in Axios?

Axios allows you to set default headers that will be sent with each request. This can be done using the defaults property of the Axios instance. You can set the defaults property of the headers object to a JavaScript object representing the header.

Can I use Axios in a Node.js environment?

Yes, Axios can be used in Node.js environments. It provides a single API for handling HTTP interfaces for XMLHttpRequests and nodes. This makes it a versatile tool for making HTTP requests in JavaScript.

How to handle responses in Axios?

When a request is made using Axios, it returns a Promise parsed as a response object. This object contains data returned from the server, the status of the request, the header, and other information. You can use the Promise's then method to handle this response.

Can I make multiple requests at the same time using Axios?

Yes, Axios allows you to make multiple requests at the same time. This can be done using Axios' all method. You pass the Promise array returned by the Axios request to the all method, which returns a new Promise that will be parsed when all requests are completed.

The above is the detailed content of Axios Beginner's Guide: A Handy Promise-based HTTP Client. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template