About the axios package commonly used in front-end development

Front end, axios, network request
About the axios package commonly used in front-end development

jcLee95's personal blog : https://blog.csdn.net/qq_28550263?spm=1001.2101.3001.5343
email address: [email protected]
article address : https://blog.csdn.net/qq_28550263/article/details/131099244


Related articles: ["Usage analysis and secondary packaging of dio module in flutter"](https://blog.csdn.net/qq_28550263/article/details/131152631](https://blog.csdn.net/qq_28550263/ article/details/131152631)


1 Overview

1.1 what is axios

Axios is a Promise-based HTTP client for sending asynchronous requests in the browser and Node.js. It is a popular JavaScript library designed to simplify the data transfer process between client and server. Axios provides a concise yet powerful API to easily perform various HTTP requests such as GET, POST, PUT, DELETE, etc.

Axios has the following features and functions:

Features describe
Promise support Axios is based on Promise and can take advantage of the advantages of Promise, such as chaining calls, error handling and asynchronous operations.
Cross browser support Axios works in both the browser and Node.js environments, providing a consistent API.
Automatically convert data Axios can automatically convert request and response data into different formats such as JSON, XML, FormData, etc.
interceptor Axios provides request and response interceptors, which can intercept and process the request before it is sent and after the response is returned.
cancel request Axios supports the function of canceling the request, which can abort the ongoing request when needed.
error handling Axios provides a global error handling mechanism, which can easily capture and process errors in the request process.
Prevent CSRF Axios can prevent cross-site request forgery by setting request headers or using CSRF tokens.

Axios is a powerful, easy-to-use, and widely adopted HTTP client library that helps developers easily interact with servers. Whether handling simple API requests or dealing with complex network communications, Axios provides a simple and flexible set of tools to meet various needs. Readers can read the axios Chinese translation document in the following blog post: "Axios Document Chinese Translation" , address: https://blog.csdn.net/qq_28550263/article/details/122537980

1.2 About this article

2. Start with the basic usage of axios

2.1 Introduction to axios usage

2.1.1 Install and import axios module

npm install axios
# or
yarn add axios
# or
pnpm i axios

After the installation is complete, you can import axios as follows:

import axios from 'axios';

2.1.2 Send GET request

axios.get('/api/data')
  .then((response) => {
    
    
    // 处理成功响应
    console.log(response.data);
  })
  .catch((error) => {
    
    
    // 处理错误响应
    console.error(error);
  });

2.1.3 Send POST request

axios.post('/api/data', {
    
     /* 数据 */ })
  .then((response) => {
    
    
    // 处理成功响应
    console.log(response.data);
  })
  .catch((error) => {
    
    
    // 处理错误响应
    console.error(error);
  });

2.2 Why do you need to encapsulate axios

Although axios can be used directly for basic requests, there are some inconveniences in unencapsulated axios:

  1. Code redundancy : It is necessary to repeatedly write logic such as request configuration and error handling in each request, resulting in code redundancy and reduced readability.
  2. Inconsistent configuration : If axios is used in multiple places in the project, the configuration in each place may be inconsistent, resulting in inconsistent code style.
  3. Lack of interceptors : Unencapsulated axios has no predefined request and response interceptors, and cannot conveniently process request and response logic uniformly, such as authentication and error handling.
  4. Difficulty in API management : Unencapsulated axios cannot easily manage API interfaces, which can easily lead to scattered interface definitions, making it difficult to find and modify.
  5. Limited scalability : unencapsulated axios is difficult to extend functions, such as adding custom interceptors, caching and other functions.

To sum up, encapsulating axios can solve the inconvenience of unencapsulated axios and provide better code organization, maintainability and scalability. Through encapsulation, it can be configured uniformly, provide interceptor processing, facilitate API management, and make the code more concise, readable and easy to maintain. To sum up, there are several reasons for encapsulating axios:

  • Code reuse : Through encapsulation, general request logic can be encapsulated into reusable functions or modules, reducing the writing of repetitive code.
  • Maintainability : Encapsulate logic such as axios configuration and interceptors in one place for easy maintenance and modification.
  • Error handling : Encapsulation can centrally process errors of requests and responses, and provide a unified error handling mechanism.
  • Unified management of interfaces : The definition and management of API interfaces are centralized in one place, making it easy to search and modify.
  • Easy to expand : Through encapsulation, the functions of axios can be easily extended, such as adding authentication, caching and other functions.

3. Encapsulation of axios

When wrapping axios, it can take different forms. The following introduces function encapsulation, instance encapsulation and class encapsulation respectively, and gives the specific encapsulation sample code written in TypeScript:

3.1 Function encapsulation method

Function encapsulation is to encapsulate commonly used requests into functions, receive parameters and return Promise objects.

import axios, {
    
     AxiosRequestConfig, AxiosResponse } from 'axios';

/**
 * 发送GET请求
 * @param url 请求URL
 * @param params 请求参数
 * @returns Promise对象,包含响应数据
 */
export function get(url: string, params?: AxiosRequestConfig['params']): Promise<AxiosResponse> {
    
    
  return axios.get(url, {
    
     params });
}

/**
 * 发送POST请求
 * @param url 请求URL
 * @param data 请求数据
 * @returns Promise对象,包含响应数据
 */
export function post(url: string, data?: any): Promise<AxiosResponse> {
    
    
  return axios.post(url, data);
}

// 在Vue组件中使用
import {
    
     get, post } from '@/api';

export default {
    
    
  methods: {
    
    
    fetchData() {
    
    
      get('/data')
        .then((response) => {
    
    
          // 处理成功响应
        })
        .catch((error) => {
    
    
          // 处理错误响应
        });
    },
    postData() {
    
    
      post('/data', {
    
     /* 数据 */ })
        .then((response) => {
    
    
          // 处理成功响应
        })
        .catch((error) => {
    
    
          // 处理错误响应
        });
    },
  },
};

3.2 Instance encapsulation method

Instance encapsulation is to create an axios instance and set common configurations, interceptors, etc.

import axios, {
    
     AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';

class ApiClient {
    
    
  private instance: AxiosInstance;

  constructor(baseURL: string) {
    
    
    this.instance = axios.create({
    
    
      baseURL,
      timeout: 5000,
    });

    // 请求拦截器
    this.instance.interceptors.request.use(
      (config) => {
    
    
        // 在请求发送前做一些处理
        return config;
      },
      (error) => {
    
    
        // 处理请求错误
        return Promise.reject(error);
      }
    );

    // 响应拦截器
    this.instance.interceptors.response.use(
      (response) => {
    
    
        // 对响应数据进行处理
        return response.data;
      },
      (error) => {
    
    
        // 处理响应错误
        return Promise.reject(error);
      }
    );
  }

  /**
   * 发送GET请求
   * @param url 请求URL
   * @param params 请求参数
   * @returns Promise对象,包含响应数据
   */
  public get(url: string, params?: AxiosRequestConfig['params']): Promise<AxiosResponse> {
    
    
    return this.instance.get(url, {
    
     params });
  }

  /**
   * 发送POST请求
   * @param url 请求URL
   * @param data 请求数据
   * @returns Promise对象,包含响应数据
   */
  public post(url: string, data?: any): Promise<AxiosResponse> {
    
    
    return this.instance.post(url, data);
  }
}

// 在Vue组件中使用
import ApiClient from '@/api';

const api = new ApiClient('https://

api.example.com');

export default {
    
    
  methods: {
    
    
    fetchData() {
    
    
      api.get('/data')
        .then((response) => {
    
    
          // 处理成功响应
        })
        .catch((error) => {
    
    
          // 处理错误响应
        });
    },
    postData() {
    
    
      api.post('/data', {
    
     /* 数据 */ })
        .then((response) => {
    
    
          // 处理成功响应
        })
        .catch((error) => {
    
    
          // 处理错误响应
        });
    },
  },
};

3.3 Class encapsulation method

Class encapsulation encapsulates axios through classes, encapsulating various request methods and processing logic. For example:

import axios, {
    
     AxiosRequestConfig, AxiosResponse } from 'axios';

class ApiClient {
    
    
  private baseURL: string;
  private instance = axios.create({
    
    
    timeout: 5000,
  });

  constructor(baseURL: string) {
    
    
    this.baseURL = baseURL;

    // 请求拦截器
    this.instance.interceptors.request.use(
      (config) => {
    
    
        // 在请求发送前做一些处理
        return config;
      },
      (error) => {
    
    
        // 处理请求错误
        return Promise.reject(error);
      }
    );

    // 响应拦截器
    this.instance.interceptors.response.use(
      (response) => {
    
    
        // 对响应数据进行处理
        return response.data;
      },
      (error) => {
    
    
        // 处理响应错误
        return Promise.reject(error);
      }
    );
  }

  /**
   * 发送GET请求
   * @param url 请求URL
   * @param params 请求参数
   * @returns Promise对象,包含响应数据
   */
  public get(url: string, params?: AxiosRequestConfig['params']): Promise<AxiosResponse> {
    
    
    return this.instance.get(this.baseURL + url, {
    
     params });
  }

  /**
   * 发送POST请求
   * @param url 请求URL
   * @param data 请求数据
   * @returns Promise对象,包含响应数据
   */
  public post(url: string, data?: any): Promise<AxiosResponse> {
    
    
    return this.instance.post(this.baseURL + url, data);
  }
}

// 在Vue组件中使用
import ApiClient from '@/api';

const api = new ApiClient('https://api.xxxxxx.com');

export default {
    
    
  methods: {
    
    
    fetchData() {
    
    
      api.get('/data')
        .then((response) => {
    
    
          // 处理成功响应
        })
        .catch((error) => {
    
    
          // 处理错误响应
        });
    },
    postData() {
    
    
      api.post('/data', {
    
     /* 数据 */ })
        .then((response) => {
    
    
          // 处理成功响应
        })
        .catch((error) => {
    
    
          // 处理错误响应
        });
    },
  },
};

3.4 Comparison of three packaging methods

Above we introduced the encapsulation of axios through three encapsulation methods: function encapsulation , instance encapsulation , and class encapsulation . Of course, they can all be used to encapsulate axios, and they have some differences in code organization and use. In this section we make some comparisons of these three methods.

Encapsulation describe
Function encapsulation The function encapsulation method is the simplest encapsulation method. It passes in axios as a function parameter and executes the corresponding request inside the function.
This method is suitable for simple request scenarios, and can quickly send requests and get responses.
The main advantage of the function encapsulation method is that it is easy to use, without additional complexity, and is suitable for small projects or situations with only a few API requests. However, the scalability of the function encapsulation method is relatively poor, and it is difficult to handle complex request logic and unified error handling.
Instance encapsulation The instance encapsulation method creates an axios instance and encapsulates different types of requests by adding methods to the instance.
This way you can set common request configuration in an instance, such as base URL, interceptor, etc.
The instance encapsulation method has better scalability and flexibility, and multiple instances can be defined as required, and each instance can have its own configuration. This method is suitable for medium and large projects, and can better organize and manage request codes.
class encapsulation The class encapsulation method uses object-oriented thinking, encapsulates axios into a class, and sends requests through the methods of the class.
This method combines the advantages of function encapsulation and instance encapsulation, and provides more powerful encapsulation capabilities and better code organization structure.
Class encapsulation can define common request configuration and error handling logic, and can achieve more advanced function extensions through inheritance and polymorphism. It is suitable for large projects and scenarios requiring complex request logic.

In general, the function encapsulation method is simple and easy to use, the instance encapsulation method has certain scalability and flexibility, and the class encapsulation method provides the most powerful encapsulation ability and code organization structure. Which method to choose in actual development can depend on the scale and complexity of the project, but generally depends more on the development experience of the team, as well as personal preferences and needs.

4. Thinking about abandoning Axios

4.1 The main problems of Axios

xios is a commonly used JavaScript library for making HTTP requests in browsers and Node.js. Although Axios is a popular choice, it has some drawbacks:

project describe alternate direction
Larger The relatively large size of Axios may have some negative impact on performance in some cases. If the project has strict requirements on file size, some lightweight alternatives can be considered.
API design style The API design of Axios is based on Promise, which is very convenient for handling asynchronous requests. However, some developers may prefer to use a callback-based API or async/await syntax. According to personal preferences and project requirements, it may be more appropriate to choose a suitable API style.
browser compatibility Although Axios works well in most modern browsers, there may be compatibility issues in some older versions of browsers. If you need to support older browsers, you may need to consider other solutions or additional compatibility processing.

4.2 Some Ready Alternatives

Alternative solutions are being collected, welcome to leave a message in the comment area to recommend

plan describe document link
Fetch API The Fetch API is an interface provided natively by modern browsers for initiating network requests. It supports Promise and async/await syntax. It has a small size and has good compatibility in most modern browsers. https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API
Superagent Superagent is another popular HTTP request library with clean API design and small size. It supports both callback and Promise flavors, and works both in the browser and in Node.js. https://ladjs.github.io/superagent/docs/zh_CN/index.html
Fetch+AbortController If you're only concerned with compatibility with modern browsers, you can use the Fetch API in conjunction with the AbortController to initiate requests and support request cancellation. AbortController allows you to cancel ongoing requests when needed, which can be very useful in some situations. https://developer.mozilla.org/zh-CN/docs/Web/API/AbortController

5. Fetch

5.1 Introduction to Fetch

5.1.1 What is Fetch

In the past, front-end developers usually used the XMLHttpRequest object to make network requests. However, XMLHttpRequest has some problems, such as using cumbersome interface, non-uniform syntax and difficult to handle errors. In order to solve these problems, W3C (World Wide Web Consortium) and the Web development community worked together to develop the Fetch API. Fetch is a modern web API for making network requests in the front end. It provides an alternative to traditional XMLHttpRequest (XHR) to handle network communication in a simpler, flexible and unified way. The design goals of the Fetch API include:

  1. Provides a simple and powerful way to make network requests.
  2. Unify the interface and syntax of network requests, making it easier for developers to understand and use.
  3. Promise objects are supported for better handling of asynchronous requests.
  4. Provides more flexible request and response handling options.

5.1.2 Comparison between Fetch and traditional methods

Compared to using XMLHttpRequest

XMLHttpRequest 方式相比。Fetch API相对于XMLHttpRequest具有以下优势:

项目 描述
更简洁的语法 Fetch API使用Promise和链式调用的方式,使代码更易读和组织。
内置的JSON解析 Fetch API内置了将响应数据解析为JSON的方法,不需要手动解析。
支持流数据 Fetch API可以处理流数据,而XMLHttpRequest不支持。
更灵活的请求选项 Fetch API提供了更丰富的请求选项,如headers、mode、cache等。
更好的错误处理 Fetch API使用Promise的catch方法来处理错误,比传统方式更直观。

对比使用 axios 模块

axios 的比较第三方模块对比:

对比项 描述
API设计 Fetch API的API设计更现代化和简洁,使用Promise和链式调用。而axios使用传统的回调函数方式设计API。
兼容性 Fetch API在现代浏览器中有良好的支持,但在老旧浏览器中存在兼容性问题。而axios通过封装XMLHttpRequest对象,具有更好的兼容性。
功能扩展 axios提供了一些额外的功能,如请求取消、拦截器、请求重试等,而Fetch API没有内置这些功能,需要开发人员自行实现。
请求转换 axios支持请求和响应的数据转换,可以自动将请求和响应数据转换为JSON、FormData等格式。Fetch API需要手动处理数据转换。
浏览器环境外支持 axios可以在浏览器和Node.js环境中使用,而Fetch API主要用于浏览器环境。

选择使用Fetch API还是axios取决于具体需求和项目要求。如果希望使用原生的浏览器API并且在现代浏览器中运行,可以考虑使用 Fetch API。如果需要更多的功能扩展、兼容性和数据转换支持,尚且还可以继续使用 axios。

5.1 Fetch 用法

5.2.1 快速入门

使用 Fetch API可以轻松地发起各种类型的HTTP请求并处理响应数据,本节给一个基本的Fetch请求示例:

fetch('https://api.xxxxxx.com/data')
  .then((response: Response) => {
    
    
    if (!response.ok) {
    
    
      throw new Error('网络响应不正常');
    }
    return response.json();
  })
  .then((data: any) => {
    
    
    console.log(data);
  })
  .catch((error: Error) => {
    
    
    console.error('Error:', error);
  });

这个例子中,我们使用 fetch 函数发起了一个 GET 请求,并指定了要请求的 URL。然后,我们使用 Promisethen 方法处理响应。如果响应的状态码 不是200 时我们抛出一个错误。否则,我们将响应数据解析为 JSON 格式并输出到控制台。

5.2.2 Fetch的请求选项

Fetch API提供了一些可选的请求选项,用于自定义请求的行为。以下是一些常用的选项:

选项 描述
method 指定请求的 HTTP 方法,如 GETPOSTPUTDELETE
headers 设置请求的头部信息,如 Content-TypeAuthorization
body 设置请求的主体数据,可以是字符串、FormData对象等
mode 设置请求的模式,如 corsno-corssame-origin
cache 设置请求的缓存模式,如 defaultno-storereload

例如:

const options: RequestInit = {
    
    
  method: 'POST',
  headers: {
    
    
    'Content-Type': 'application/json',
    'Authorization': 'Bearer token'
  },
  body: JSON.stringify({
    
     username: 'john', password: 'secret' })
};

fetch('https://api.example.com/login', options)
  .then((response: Response) => {
    
    
    if (!response.ok) {
    
    
      throw new Error('网络响应不正常');
    }
    return response.json();
  })
  .then((data: any) => {
    
    
    console.log(data);
  })
  .catch((error: Error) => {
    
    
    console.error('Error:', error);
  });

【注】

5.2.3 Fetch 的响应处理

Fetch API提供了多种处理响应的方法,您可以根据需要选择适合的方法。以下是一些常用的处理方法:

方法 描述
response.text() 将响应数据作为文本返回。
response.json() 将响应数据解析为JSON格式返回。
response.blob() 将响应数据解析为Blob对象返回。
response.arrayBuffer() 将响应数据解析为ArrayBuffer对象返回。

例如:

fetch('https://api.example.com/image')
  .then((response: Response) => {
    
    
    if (!response.ok) {
    
    
      throw new Error('网络响应不正常');
    }
    return response.blob();
  })
  .then((blob: Blob) => {
    
    
    const img = document.createElement('img');
    img.src = URL.createObjectURL(blob);
    document.body.appendChild(img);
  })
  .catch((error: Error) => {
    
    
    console.error('Error:', error);
  });

本例我们使用 response.blob() 方法将响应数据解析为 Blob对象。然后,我们创建一个img 元素,并将 Blob 对象的 URL 赋值给 imgsrc 属性,以显示图像。

Guess you like

Origin blog.csdn.net/qq_28550263/article/details/131099244
Recommended