Axios an HTTP client based on promises.

In general, using Axios requires secondary encapsulation, and this blog is thinking about it from that perspective.

Install axios

yarn add axios
Copy the code

Using axios

axios({
  method: 'GET'.url: 'your url',})Copy the code

The above code shows that a get request is used to request the link “your URL “, and axios also supports PUT, POST, DELETE, and other request methods.

Response of the structure

The document is here

The structure directory is:

{
  data: {},
  status: 200.statusText: 'OK'.headers: {},
  config: {},
  request: {},}Copy the code

Axios returns a promise, which means you can use.then() and async/await methods and keywords.

Encapsulation axios

Start by creating an axios instance

const request = axios.create({
  baseURL: 'http://example.com/api'.timeout: 5000,})Copy the code

The above code is used to create the simplest example with the following functionality: each request will start with ‘example.com/api’ and each request will timeout for 5 seconds.

Request interceptor

The interceptor documentation is here.

Add request interceptor:

axios.interceptors.request.use(
  (config) = > {
    // you want to do things
  },
  (error) = > {
    // Request error handling})Copy the code

There are many things you can do here, such as intercepting duplicate requests, adding headers to the request, determining whether you are logged in now, and loading globally.

If you need to remove a request interceptor, you need to:

axios.interceptors.request.eject(myInterceptor)
Copy the code

Response interceptor

Add response interceptor:

axios.interceptors.response.use(
  (response) = > {
    // you want to do things
  },
  (error) = > {
    // Response error handling})Copy the code

You can also do a lot of things here, such as handling errors globally and eliminating loading globally.

If you need to remove a response interceptor, you need to:

axios.interceptors.response.eject(myInterceptor)
Copy the code

The following examples include intercepting repeated requests, adding headers, adding global loading, and handling global errors.

An example of wrapping AXIos

Here is an example of wrapping AXIOS

The default configuration creates an axiOS instance

  1. Creating a request instance
  2. Default configuration
const service = axios.create({
  url: 'http://example.com/api'.timeout: 5000});Copy the code

Add request interceptors and response interceptors

service.interceptor.request.use(
  (config) = >{},(error) = >{}); service.interceptor.response.use((config) = >{},(error) = >{})Copy the code

Add headers to each request

For example, the login request needs to carry token, and each request needs to carry token authentication, this can be added to the “request interceptor”.

service.interceptor.request.use(
  (config) = > {
    const token = localStorage.getItem('token')
    config.headers.Authorization = token

    return config
  }
)
Copy the code

Add global loading

In this example, the UI component library uses Element Plus. You can use other component libraries as well. There is no limit to this.

  1. Start loading at request time
  2. End loading when the request ends
const showLoading = null

service.interceptor.request.use(
  (config) = > {
    // Use loading globally
    showLoading = ElLoading.service({ fullscreen: true })

    const token = localStorage.getItem('token')
    config.headers.Authorization = token

    return config
  }
)

service.interceptor.response.use(
  (config) = > {
    // Disable loading globally
    if (showLoading) showLoading.close()

    return config.data
  }
)
Copy the code

Global processing error

Use response interceptors to handle interface return errors.

service.interceptor.response.use(
  (config) = > {
    if (showLoading) showLoading.close()

    const { data: { code, message } } = config

    switch (true) {
      case / 1 /.test(code):
      case / 200 /.test(code):
        ElMessage({
          type: 'success',
          message,
          showClose: true,})break

      default:
        break
    }

    return config.data
  },
  (error) = > {
    // If the request fails, the global loading must be cleared
    if (showLoading) showLoading.close()

    const { code } = error.response

    switch(true) {
      case / 401 /.test(code):
        ElMessage({
          type: 'error'.message: 'Unauthenticated, please log in! '.showClose: true,
        })

        router.push('/ 401')
        // or
        router.push('login')
        break

      default:
        break}})Copy the code

Intercepting repeated requests

Sometimes multiple requests are made, at which point you need to cancel the previous request and only respond to the last one.

// Store pending requests
const taskList = new Map()

service.interceptor.request.use(
	(config) = > {
    // Use loading globally
    showLoading = ElLoading.service({ fullscreen: true })

    const token = localStorage.getItem('token')
    config.headers.Authorization = token

    // If there was a request pending, cancel that request; If no request has been made, the cancel method is saved.
    if (taskList.has(config.url)) {
     	const cancel = taskList.get(config.url)
      cancel(config.url)
      taskList.delete(config.url)
    } else {
      new axios.CancelToken((cancel) = > {
        taskList.set(config.url, cancel)
      })
    }

    return config
  }
)
Copy the code

That’s pretty much the end of the example, but there are a few issues, such as: if a page is requested many times, it will cause a lot of popovers, which will affect the aesthetics. My solution is that each popover will only appear once at a time. But it’s missing some key information, so you get what you give.

The solution is a matter of opinion.

The principle of axios

The essence of Axios is that it encapsulates XHR, and AXIos makes it much more usable.

  1. XMLHttpRequest
  2. http

Details can be found at: github.com/axios/axios…

  • Introduce the XMLHttpRequest
  • Read the axios source code