vue2 uses axios

Integrating and using Axios for HTTP request operations in Vue 2 typically includes the following steps:

1. Install Axios:

Install Axios through npm or yarn in the project directory.

npm install axios
# or
yarn add axios 

2. Global configuration and registration

For easy access to the Axios for all Vue components, it can be mounted on the prototype of the Vue so that each component can be accessed through the this. $http to call Axios.

Configure the following in the main.js file:

import axios from 'axios';
import Vue from 'vue';

// Set default configuration(Optional)
axios.defaults.baseURL = process.env.VUE_APP_API_BASE_URL; // set up API Base URL

// Will axios mount to Vue.prototype superior
Vue.prototype.http = axios;

// Create and use a custom instance(Optional)
const request = axios.create({
    headers: {'Content-Type': 'application/json;charset=UTF-8'},
    // Other custom configuration items...
});
Vue.prototype.api = request; // If you need to distinguish between different types of requests,Multiple instances can be created and mounted separately

new Vue({
    render: h => h(App),
}).$mount('#app'); 

III. Basic Use:

Get request initiated by •:

this.$http.get('/api/users')
.then(response => {
    console.log(response.data);
    // Processing success callback logic
})
.catch(error => {
    console.error(error);
    // Handle error callback logic
}); 

Initiate a POST request and if you need to send data in JSON format:

let data = { name: 'John', age: 30 };
this.$http.post('/api/users', data)
.then(response => {
    // ...
})
.catch(error => {
    // ...
}); 

IV. Interceptor Settings:

You can set the request/response interceptor to process global request prefixes, add JWT token, and so on:

axios.interceptors.request.use(config => {
    const token = localStorage.getItem('token'); // Obtain token Example
    if (token) {
    config.headers.Authorization = `Bearer ${token}`; // Set request header
    }
    return config;
}, error => Promise.reject(error));

// Add response interceptor
axios.interceptors.response.use(response => {
    // Unified processing of response data,Such as error code judgment, etc.
    return response;
}, error => {
    // Unified handling of response errors,Such as pop-up notification or redirect login page
    return Promise.reject(error);
}); 

V. Use in combination with async/await:

In Vue components where methods or other async functions are supported, async/await can be combined to simplify asynchronous operations:

async fetchData() {
    try {
    const response = await this.$http.get('/api/data');
    this.someData = response.data;
    } catch (error) {
    console.error('Fetch data failed:', error);
    }
} 

These are the basic steps for how to use Axios in Vue 2.

Depending on actual project requirements, Axios instances can also be further encapsulated to provide more business-logical APIs.

****Vue package axios****

Encapsulating Axios API in Vue.js simplifies request processing and provides unified error handling, default configuration, and data formatting. The following is an example of a simple Axios package:

// Create a file named AxiosApi document,For example:Axios.js

import axios from 'axios'; // (Optional)If you wish to use axios of CancelToken to support cancellation requests

let cancelTokenSource = null; // for canceling requests(Only when using axios hour)

function createCancelToken() {
  // If you choose to use axios of CancelToken Function
  if (axios) {
    cancelTokenSource = axios.CancelToken.source();
    return cancelTokenSource.token;
  }
  // If not used axios,You can ignore this part
  return null;
}

export default async function AxiosApi(url, options = {}) {
  const { method = 'GET', body, headers = {}, params, isJson = true } = options;

  // Add global request headers or other default configuration
  headers['Content-Type'] = isJson ? 'application/json' : headers['Content-Type'] || 'text/plain';

  // deal with GET Request parameters
  if (method === 'GET' && params) {
    url = new URL(url, window.location.origin);
    Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
  }

  // Create a cancellation request token(If using axios)
  const cancelToken = createCancelToken();

  try {
    const response = await Axios(url, {
      method,
      headers,
      ...(body && { body: isJson ? JSON.stringify(body) : body }), // for POST/PUT etc.,send JSON format data
      ...(cancelToken && { signal: cancelTokenSource.token }), // If there is a cancel request function,Pass signal object
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = isJson ? await response.json() : await response.text(); // Parse the response content as needed as JSON or text

    return {
      success: true,
      data,
      message: 'Request successful',
    };
  } catch (error) {
    // in the case of Axios Cancellation error,then identify
    if (axios.isCancel(error)) {
      console.error('Request canceled', error.message);
      return {
        success: false,
        message: 'Request canceled',
      };
    }

    console.error('Axios API Request failed', error);
    return {
      success: false,
      message: 'Server exception,Please try again later',
    };
  }
} 

Then, introduce and use this encapsulated AxiosApi function in your Vue component:

import AxiosApi from './Axios.js';

export default {
  name: 'MyComponent',
  methods: {
    async AxiosData() {
      const response = await AxiosApi('/api/data', {
        method: 'GET',
        params: { id: 1 },
      });

      if (response.success) {
        this.data = response.data;
      } else {
        // handling errors
      }
    },
  },
  mounted() {
    this.AxiosData();
  },
}; 

The above code encapsulates the basic usage of Axios API and provides a degree of error handling and default configuration. You can expand it to suit the specific needs of the project, such as adding interceptors, adding authentication information, processing paging, and so on.

This document is transferred from https://blog.csdn.net/bjzhang75/article/details/138473186,If there is any infringement,Please contact to delete。.