SoFunction
Updated on 2025-04-06

Encapsulate the axios sample code in vue for details

In the vue project, when interacting with the background to get data, we usually use the axios library, which is a promise-based http library that can be run on the browser side and in the browser. It has many excellent features, such as intercepting requests and responses, canceling requests, converting json, client defense cSRF, etc. So our Youda also decisively gave up the maintenance of its official library vue-resource and directly recommended that we use the axios library. If you still don't know anything about axios, you can moveaxios documentation.

Install

npm install axios; // Install axios

Okay, let’s start today’s main text.

This package is used to solve the problem: (For login function, you can use it directly, and other network requests can also be used directly. If you have a cleanliness, you can delete a few lines of code related to token)

ps: When using it, when importing axios: import axios from 'name and relative path of this file'

  • Accept the background token
  • Automatic conversion of post parameters, omitted ()
  • The background token will automatically clear the local data after it expires, so that you can enter your account password again next time
  • Better error message
/**
  * Encapsulate network requests
  */
import axios from "axios"
import qs from "querystring"
import store from '../store'
import router from '../router'
//Return to login interface after token expiresconst toLogin = () =>{
 ("/login")
}
// Error message response methodconst errroHandle = (status,other) => {
 switch(status){
  case 400:
   ("The server cannot understand the request information");
   break;
  case 401:
   ("User information verification failed");
   ("token"); // Optional   toLogin();
   break;
  case 403:
   ("Requests are restricted");
   ("token"); // Optional   toLogin();
   break;
  case 404:
   ("Client request information error");
   break;
  default:
   (other);
   break;
 }
}
// Create an axios objectconst instance = ({
 timeout:5000
})
// Hang in the global object = "";
['Content-Type'] = 'application/x-www-form-urlencoded';
// Interceptor: Request interception and response interception Post request parameters need to be transcoded// The return value object of axios is required to be a promise object(config =>{
 if( === "post"){
   = ()
 }
 if(){
   = ;
 }
 return config;
},error => (error))
(
 // success response =>  === 200 ? (response) :(response),
 // fail error => {
  const { response } = error;
  if(response){
   errroHandle(,)
   return (response)
  }else{
   // No error message can be returned   ("Request interrupted");
  }
 }
)
export default instance

Summarize

The above is a detailed explanation of the axios sample code in vue introduced by the editor. I hope it will be helpful to everyone!