This HTTP Request Library Makes API Calls More Elegant – Axios

Getting Started Tutorial

Friends, today we are going to discuss an essential topic in front-end development – HTTP Requests. Whether it’s fetching data from the backend or sending form information to the server, we cannot do without HTTP request tools. Today, I will introduce you to a library that makes API calls more elegant – Axios.

Compared to the built-in <span>fetch</span> in browsers, Axios is a feature-rich and easy-to-use HTTP request library that makes our network request handling more efficient and elegant. Next, we will learn the basic usage of Axios together and gradually master its powerful features through examples!

1. Why Choose Axios?

Before we start learning, let’s take a look at the features of Axios and why it is more convenient than the native <span>fetch</span>:

  • Simple and Easy to Use: Axios’s API is more concise and intuitive, resulting in less code when handling requests.
  • Automatic JSON Parsing: No need to manually call <span>.json()</span>, the returned data is already parsed into an object.
  • Supports Interceptors: You can uniformly handle logic before a request is sent or after a response is received.
  • Automatic Timeout and Error Handling: Built-in timeout functionality and a more user-friendly error handling method.
  • Supports Request Cancellation: You can cancel HTTP requests when needed.

These features make Axios the preferred HTTP request tool in many projects.

2. Installing Axios

To use Axios, you first need to install it. Run the following command in your project directory:

npm install axios

Once installed, you can happily use it in your project!

3. Basic Usage: Sending a GET Request

Let’s start with the simplest Axios request. Suppose we want to fetch user data from a public API:

import axios from "axios";

// Send a GET request
axios.get("https://jsonplaceholder.typicode.com/users")
  .then((response) => {
    console.log(response.data); // Output user data
  })
  .catch((error) => {
    console.error("Request failed:", error);
  });

Code Explanation

  1. **<span>axios.get(url)</span>**: Sends a GET request to the specified URL.
  2. **<span>then</span>**: The data returned after a successful request will be placed in <span>response</span>, and <span>response.data</span> is the parsed data.
  3. **<span>catch</span>**: If the request fails, it will enter the <span>catch</span>, where you can handle the error.

After running the above code, you will see the user data returned by the API in the console.

4. Sending a POST Request

In addition to GET requests, we can also use Axios to send POST requests. For example, we want to submit a new post to the server:

axios.post("https://jsonplaceholder.typicode.com/posts", {
  title: "Hello World",
  body: "This is a test post.",
  userId: 1,
})
  .then((response) => {
    console.log("New post created successfully:", response.data);
  })
  .catch((error) => {
    console.error("Failed to create post:", error);
  });

Code Explanation

  1. **<span>axios.post(url, data)</span>**: The first parameter is the URL, and the second parameter is the data to be sent.
  2. The data will be automatically converted to JSON and sent to the server.
  3. The response data returned by the server can be viewed in <span>response.data</span>.

5. Axios Configuration: Making Requests More Elegant

In actual projects, it is often necessary to repeatedly call the same API, such as with a fixed base URL or headers. In this case, you can use Axios’s global configuration feature.

5.1 Creating an Axios Instance

We can create an Axios instance and set default configurations:

const apiClient = axios.create({
baseURL: "https://jsonplaceholder.typicode.com", // Base URL
timeout: 5000, // Timeout duration
headers: { "Content-Type": "application/json" }, // Default request headers
});

// Use the instance to send requests
apiClient.get("/users")
  .then((response) => {
    console.log("User data:", response.data);
  })
  .catch((error) => {
    console.error("Request failed:", error);
  });

Code Explanation

  1. **<span>axios.create(config)</span>**: Creates an Axios instance using a configuration object.
  2. **<span>baseURL</span>**: Sets the base path, which will be automatically appended to all requests.
  3. **<span>timeout</span>**: Sets the timeout duration to avoid requests hanging.

Tip

  • After creating an Axios instance, subsequent requests will be more concise, improving code maintainability.
  • If the API requires authentication, such as carrying a token, it can be uniformly configured in the headers.

6. Using Interceptors: Unified Handling of Requests and Responses

Axios provides the interceptor feature, which allows you to uniformly handle logic before a request is sent or after a response is received, avoiding repetitive code.

6.1 Adding Request Interceptors

We can automatically add a token before each request:

apiClient.interceptors.request.use(
  (config) => {
    config.headers.Authorization = "Bearer your-token"; // Add Token
    console.log("Request Interceptor:", config);
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

6.2 Adding Response Interceptors

You can uniformly handle errors or data formats after the response is received:

apiClient.interceptors.response.use(
  (response) => {
    console.log("Response Interceptor:", response);
    return response.data; // Directly return the parsed data
  },
  (error) => {
    console.error("Response Error:", error.response?.data || error.message);
    return Promise.reject(error);
  }
);

Tip

Interceptors are a great place to handle global logic, such as unified error handling, checking login status, etc.

7. Practical Exercise: Try These Tasks!

  1. Use Axios to implement a simple user list page that displays users’ names and emails.
  2. Add a form to submit new user information to the server via Axios.
  3. Use interceptors to print the request URL and method for each request.

8. Summary

Today, we learned how to use Axios to send HTTP requests. Compared to the native <span>fetch</span>, Axios provides a more elegant API and rich features, such as:

  • Simple GET and POST requests.
  • Creating instances to manage request configurations.
  • Using interceptors to handle logic uniformly.

In actual projects, Axios can greatly simplify the code for network requests and improve development efficiency.

Friends, today’s JS learning journey ends here! Remember to code along, and feel free to ask questions in the comments. Wishing everyone a happy learning experience and continuous improvement in JavaScript!

Leave a Comment