What is the method for encapsulating request interfaces in axios?

One way to encapsulate request interfaces using axios is by creating an axios instance and using that instance to send requests. Here is an example of how to encapsulate a request interface using axios.

import axios from 'axios';

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

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

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

In the example above, an axios instance was created with a base URL, timeout, and request headers set. GET and POST request methods were then wrapped using instance.get and instance.post to send the requests. This way, you can directly call the get and post methods in your project to send requests, and receive results or error messages through Promise’s resolve and reject upon success or failure.

bannerAds