How to encapsulate axios request interface?

To encapsulate axios request interface, you can follow the steps below:

  1. To install axios: use npm or yarn to install the axios library, you can execute the following command in the command line:
npm install axios

Perhaps

yarn add axios
  1. Create a file named api.js: Create a file named api.js in the src directory of the project, and import the axios library into the file.
import axios from 'axios';

// 创建axios实例
const service = axios.create({
  baseURL: 'http://api.example.com',  // 设置接口的基础url
  timeout: 5000  // 设置超时时间
});

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 在发送请求之前可以进行一些处理,如添加token等
    return config;
  },
  error => {
    // 请求错误时的处理
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  response => {
    // 对响应数据进行处理,如统一处理错误信息等
    return response.data;
  },
  error => {
    // 响应错误时的处理
    return Promise.reject(error);
  }
);

export default service;
  1. Using the encapsulated axios interface: In places where axios requests are needed, you can import the api.js file and use the encapsulated axios interface for the request operation, for example:
import api from './api';

// 使用get请求
api.get('/user')
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });

// 使用post请求
api.post('/user', { name: 'John' })
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });

This completes the operation of encapsulating axios request interfaces. In use, common request methods such as get, post, put, delete, etc. can be further encapsulated according to actual needs to facilitate their use in the project.

bannerAds