SoFunction
Updated on 2025-04-04

The role of using axios in vue

What is Axios

Axios is a Promise-based HTTP client library for sending HTTP requests and processing responses. It can be used in browsers and environments and provides many features such as intercepting requests and responses, converting requests and responding to data, canceling requests, etc.

Use scenarios:

Send AJAX request: Axios can be used to send requests of GET, POST, PUT, DELETE and other types to obtain and submit data to the server.

  • Processing API requests: Axios can be used to interact with backend APIs, obtain data, display or process it.
  • File upload and download: Axios supports sending file upload requests, and can also be used to download files.

advantage:

Easy to use: Axios provides a clean API and consistent syntax, making sending requests and processing responses very easy.

  • Support Promise: Axios is based on Promise implementation, and can use async/await or .then/.catch to handle asynchronous operations, making the code clearer and easier to read.
  • Support interceptors: Axios provides request and response interceptors, which can perform some processing before and after the response is returned, such as adding request headers, handling errors, etc.
  • Support cancellation requests: Axios provides the function of canceling requests, which can interrupt ongoing requests and avoid unnecessary network requests.

shortcoming:

Larger size: The Axios library has a relatively large volume. If the project requires high volume, you can consider using other lighter HTTP libraries.

  • Not supported on lower version browsers: Axios does not support IE8 and below browsers. If you need to be compatible with lower version browsers, you need to use other compatibility solutions.

Overall, Axios is a powerful and easy-to-use HTTP library suitable for most front-end projects. It provides a wealth of features and flexible configuration options to meet the needs of different projects.

Using Axios for network requests in Vue 2 is a common practice. Axios is a Promise-based HTTP client that can send HTTP requests in the browser and in the browser. Here are the basic steps to use Axios in Vue 2:

Install Axios: First, install Axios in the project. You can use npm or yarn to install Axios, open the terminal and run the following command:

npm install axios

or

yarn add axios

Import Axios: In the components that need to use Axios, import the Axios library. You can add the following code to the script tag of the component:

import axios from 'axios';

Send GET request: Use Axios to send a GET request, you can call Axios' get method in the component's method and pass in the requested URL. Here is an example:

('/data', { name: 'John', age: 30 })
  .then(response => {
    // Process response data    ();
  })
  .catch(error => {
    // Handle errors    (error);
  });

Send POST request: If you need to send a POST request, you can use Axios' post method and pass in the requested URL and the data to be sent. Here is an example:

import axios from 'axios';
// Create an Axios instanceconst instance = ({
  baseURL: '', // Set the basic URL  timeout: 5000, // Set the request timeout time});
// Request an interceptor(
  config => {
    // Some processing can be done here before the request is sent, such as adding a request header     = 'Bearer ' + ('token');
    return config;
  },
  error => {
    // Processing request error    return (error);
  }
);
// Response Interceptor(
  response => {
    // Some processing can be done here before the response returns, such as handling errors    if ( !== 200) {
      return ();
    }
    return response;
  },
  error => {
    // Handle response errors    return (error);
  }
);
const request = {
  get(url, params = {}) {
    return (url, { params });
  },
  post(url, data) {
    return (url, data);
  },
  put(url, data) {
    return (url, data);
  },
  upload(url, file) {
    const formData = new FormData();
    ('file', file);
    return (url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  },
};
export default request;

The above is a basic example of using Axios for GET and POST requests. You can also use other methods of Axios, such as put, delete, etc., to choose the appropriate method according to your needs. At the same time, you can also set more advanced usages such as request headers and passing parameters in the request. Detailed Axios documentation can be found on the official website: /docs/intro

Encapsulation axios

When encapsulating Axios' request method, you can set the request header and handle errors. Here is an example showing how to encapsulate get, post, put, and upload methods, set request headers and handle errors:

import axios from 'axios';
// Create an Axios instanceconst instance = ({
  baseURL: '', // Set the basic URL  timeout: 5000, // Set the request timeout time});
// Request an interceptor(
  config => {
    // Some processing can be done here before the request is sent, such as adding a request header     = 'Bearer ' + ('token');
    return config;
  },
  error => {
    // Processing request error    return (error);
  }
);
// Response Interceptor(
  response => {
    // Some processing can be done here before the response returns, such as handling errors    if ( !== 200) {
      return ();
    }
    return response;
  },
  error => {
    // Handle response errors    return (error);
  }
);
const request = {
  get(url, params = {}) {
    return (url, { params });
  },
  post(url, data) {
    return (url, data);
  },
  put(url, data) {
    return (url, data);
  },
  upload(url, file) {
    const formData = new FormData();
    ('file', file);
    return (url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  },
};
export default request;

In the above example, we use Axios' interceptors property to set the request interceptor and the response interceptor. In the request interceptor, we can do some processing before the request is sent, such as adding a request header. In response interceptor, we can do some processing before the response returns, such as handling errors.

In the encapsulated get, post, put, and upload methods, we use the encapsulated Axios instance instance instance to send the request. When uploading the file, we use the FormData object to construct the request body and set the request header tomultipart/form-data

In the component that needs to send a request, you can directly import and call the corresponding method using the encapsulated request object:

import request from '@/request';
('/data', { param1: 'value1', param2: 'value2' })
  .then(response => {
    // Process response data    ();
  })
  .catch(error => {
    // Handle errors    (error);
  });
('/data', { name: 'John', age: 30 })
  .then(response => {
    // Process response data    ();
  })
  .catch(error => {
    // Handle errors    (error);
  });
('/upload', file)
  .then(response => {
    // Process response data    ();
  })
  .catch(error => {
    // Handle errors    (error);
  });

In this way, you can call the encapsulated request method more conveniently, and you can perform some general configurations in the encapsulated method, such as setting request headers, handling errors, etc.

This is the end of this article about the role of using axios in vue. For more related content about using axios for vue, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!