What is the method for encapsulating axios?

The steps for encapsulating Axios methods can be as follows:

  1. Create an axios instance: Use the method axios.create() to create an axios instance and apply some global settings, such as setting a baseURL and configuring request headers.
  2. Create a wrapper function: encapsulate various request methods as needed, such as GET, POST, etc. Within these functions, you can send requests by calling methods of the axios instance and perform some processing on the request, such as setting request headers, handling response results, etc.
  3. Export encapsulated functions: exporting encapsulated functions using export for importing and using in other places.

Here is an example code snippet for encapsulating a GET request:

import axios from 'axios';

// 创建axios实例
const instance = axios.create({
  baseURL: 'https://api.example.com', // 设置请求的baseURL
  timeout: 5000, // 设置请求超时时间
  headers: {
    'Content-Type': 'application/json', // 设置请求头的Content-Type
  },
});

// 封装GET请求方法
export function get(url, params) {
  return new Promise((resolve, reject) => {
    instance
      .get(url, { params })
      .then(response => {
        resolve(response.data);
      })
      .catch(error => {
        reject(error);
      });
  });
}

In other places, you can import the get function and call it to send a GET request.

import { get } from './api';

get('/user', { id: 1 })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });

Other types of request methods, such as POST and PUT, can also be encapsulated in a similar manner.

bannerAds