What is the method for encapsulating and using axios?

The methods for packaging and using axios are as follows:

  1. Install axios: Run the following command in your terminal to install the axios library.
npm install axios
  1. To introduce axios: In the file where you need to use it, import axios with the following code.
import axios from 'axios';
  1. receive
axios.get('/api/mydata')
  .then(function (response) {
    console.log(response.data);
  })
  .catch(function (error) {
    console.log(error);
  });
  1. publish
axios.post('/api/mydata', { name: 'John', age: 30 })
  .then(function (response) {
    console.log(response.data);
  })
  .catch(function (error) {
    console.log(error);
  });
  1. default headers
axios.defaults.headers.common['Authorization'] = 'Bearer TOKEN';
  1. request interceptors
axios.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});
  1. response interceptors
axios.interceptors.response.use(function (response) {
  // 对响应数据做些什么
  return response;
}, function (error) {
  // 对响应错误做些什么
  return Promise.reject(error);
});

These are the basic methods for packaging and using axios, which can be further configured and utilized as needed.

bannerAds