SoFunction
Updated on 2025-04-10

An article lets you understand the packaging of Axios

Preface

I have read many people on the Internet to encapsulate Axios tutorials, but there are more or less inappropriate points. Here I recommend my best practices.

The interceptor does not return data, but still returns the AxiosResponse object.

All online articles allow you to use the interceptor to directly return data. This approach is actually very inappropriate, which will make it difficult for you to expand your subsequent functions.

Not recommended practice

import Axios from 'axios'

const client = ({
  // Your configuration})

(response => {
  // The online practice is to let you return data directly  // This makes it difficult to support some subsequent functions  return 
})

export default client

Recommended practices

It is recommended to use functions instead of interceptors

import Axios, { AxiosRequestConfig } from 'axios'

const client = ({
  // Your configuration})

export async function request(url: string, config?: AxiosRequestConfig) {
  const response = await ({ url, ...config })
  const result = 
  // Your business judgment logic  return result
}

export default client

Some people may say it is too troublesome to come here, please wait and continue reading.

Add extensions to your request

Many times, our development process is like this:

Send a request => Get the data => Render content

But unfortunately, this is only ideal, in some special cases, you still need to handle exceptions or additional support, such as:

  • When the request fails, I hope to automatically retry more than 3 times before failing
  • In paging data, when a new request is issued, the last request will be automatically interrupted.
  • When a third party provides a jsonp interface, you can only use static pages (ps: Axios does not support jsonp)
  • More

When sending the above scenarios, you can only write code silently to support it, but if you do not intercept Axios' response, you can use the solution provided by the open source community.

Support request to retry

Installaxios-retry, which allows your Axios to support automatic retry function

import Axios, { AxiosRequestConfig } from 'axios'
import axiosRetry from 'axios-retry'

const client = ({
  // Your configuration})

// Install the retry plugin// When the request fails, the request will be automatically re-requested, and it will only fail after 3 failures.axiosRetry(client, { retries: 3 })

export async function request(url: string, config?: AxiosRequestConfig) {
  const response = await ({ url, ...config })
  const result = 
  // Your business judgment logic  return result
}

// It's only after 3 failures that it really failsconst data = request('/test')

PS: The axios-retry plug-in supports configuring single requests

Support jsonp requests

Install axios-jsonp, can make your Axios support the functionality of jsonp.

import Axios, { AxiosRequestConfig } from 'axios'
import jsonpAdapter from 'axios-jsonp'

const client = ({
  // Your configuration})

export async function request(url: string, config?: AxiosRequestConfig) {
  const response = await ({ url, ...config })
  const result = 
  // Your business judgment logic  return result
}

export function jsonp(url: string, config?: AxiosRequestConfig) {
  return request(url, { ...config, adapter: jsonpAdapter })
}

// You can now send a jsonp requestconst data = jsonp('/test-jsonp')

Supports URI version control

People with experience in developing Web APIs will encounter a problem. If there are major changes in the API, how can I ensure that the old version is available and release a new API?

This situation is actually not uncommon in server-side development scenarios, especially for APIs that are disclosed to the public, such as: Douban API (has expired).

Currently mainstream supports 3 types of version control:

type describe
URI Versioning Versions will be passed in the requested URI (default)
Header Versioning Custom request header will specify the version
Media Type Versioning The header of the Accept request will specify the version

URI version controlrefers to the version passed in the requested URI, e.g./v1/routeand/v2/route

import Axios, { AxiosRequestConfig } from 'axios'

const client = ({
  // Your configuration})

(config => {
  // The easiest solution   = ('{version}', 'v1')
  return config
})

// GET /api/v1/users
request('/api/{version}/users')

Header and Media Type modes can be implemented by referring to the following articles

  • Implement the Web API Versioning function
  • nest versioning

Keep request unique

On a background table page that supports page turning, a user clicks the page turning button and requests to issue a waiting response, but the user clicks search at this time and needs to re-get the data. The situation that supports you may be:

  • Request to turn the page first, search for data and then return, the data display is normal
  • Search for data first, turn page data and then return data, and the data display abnormality (usually in load balancing scenarios)

To do this, you want to be able to automatically cancel the last request, so you looked at Axios cancel request, but it needs to be used in many places, so you can encapsulate this function into an independent function.

import Axios from 'axios'

const CancelToken = 

export function withCancelToken(fetcher) {
  let abort

  function send(data, config) {
    cancel() // Cancel on your own initiative
    const cancelToken = new CancelToken(cancel => (abort = cancel))
    return fetcher(data, { ...config, cancelToken })
  }

  function cancel(message = 'abort') {
    if (abort) {
      abort(message)
      abort = null
    }
  }

  return [send, cancel]
}

use

function getUser(id: string, config?: AxiosRequestConfig) {
  return request(`api/user/${id}`, config)
}

// Package request functionconst [fetchUser, abortRequest] = withCancelToken(getUser)

// Send a request// If the last request has not been returned, it will be automatically cancelledfetchUser('1000')

// Usually no active call is required// But it can be called during the life cycle of component destructionabortRequest()

This way, when there is no need to cancel automatically, use the original function directly, and it will not affect the use of the original function.

Postscript

There are actually many things to do with Axios encapsulation, such as global error handling (also cannot affect normal requests), etc. Encapsulation should not just use the interceptor to directly return data.

In addition, the request module should be kept independent, it is recommended to expandAxiosRequestConfigOr make it into independent functions and provided to external calls to facilitate making an independent HTTP module.

Summarize

This is all about this article about packaging Axios. For more related packaging Axios content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!