SoFunction
Updated on 2025-04-03

Detailed explanation of the use and packaging of axios in vue

Share my own axios package
Axios is a very useful plug-in, all of which are params objects, so it is very convenient to do some unified processing

Of course, first of all, npm install axios. It's very simple. $ npm install axios --save
Create a new folder under src service /

Then upload the code

import axios from 'axios';
import { Toast} from 'mint-ui';// I used the mint framework to pop up my error and return. You can use other promptsimport router from '../router'

// Default timeout setting = 50000;

// Relative path settings ='';

//http request interceptor(
 config => {
  // Get token  const token = ('cc_token');
  // Set parameter format  if(!['Content-Type']){
    = {
    'Content-Type':'application/json',
   };
  }
  // Add tokens to headers  if(token){
    = token
  }
  // Authentication parameter settings  if( === 'get'){
    // Under get request, the parameters are in params, and other requests are in data    =  || {};
   let json = (());
   //Some parameters processing  }else{
    =  || {};
   //Some parameters processing  }
  return config;
 },
 err => {
  return (err);
 }
);

Some processing before the above request has been completed
Here are some processing for getting the return

//http response interceptor(
 response => {
  // Some unified code return processing  if( === 501){
   // Login verification   //I made an example to log in to the project and record the relative path   ({
    name:'login',//Which page to jump from    query:{
     retUrl:('#')[1] || '',
     is_new_user_url:1
    }
   })
  }
  return response;
 },
 error => {
  return (error)
 }
);

Then simply encapsulate all request types

/**
  * Encapsulation get method
  * @param url
  * @param params
  * @returns {Promise}
  */
export function fetch(url,params={}){
 return new Promise((resolve,reject) => {
  (url,{
   params:params
  })
   .then(response => {
    if( === 200){
    //Return successfully handled What is passed here? What is res when subsequent calls are called     resolve();//All data in our background is placed in the returned data, so it is processed here uniformly    }else{
    //Error handling     Toast()
    }
   })
   .catch(err => {
    reject(err);
    let message = 'The request failed!  Please check the network';
    //Error return    if()message=;
    Toast(message)
   })
 })
}

/**
  * Encapsulate post request
  * @param url
  * @param data
  * @returns {Promise}
  */

export function post(url,data = {}){
 return new Promise((resolve,reject) => {
  (url,data)
   .then(response => {
    if( === 200){
     resolve();
    }else{
     Toast()
    }
   },err => {
    reject(err);
    let message = 'The request failed!  Please check the network';
    if()message=;
    Toast(message)
   })
 })
}

/**
  * Encapsulate patch request
  * @param url
  * @param data
  * @returns {Promise}
  */

export function patch(url,data = {}){
 return new Promise((resolve,reject) => {
  (url,data)
   .then(response => {
    if( === 200){
     resolve();
    }else{
     Toast()
    }
   },err => {
    reject(err);
    let message = 'The request failed!  Please check the network';
    if()message=;
    Toast(message)
   })
 })
}

/**
  * Encapsulate put request
  * @param url
  * @param data
  * @returns {Promise}
  */

export function put(url,data = {}){
 return new Promise((resolve,reject) => {
  (url,data)
   .then(response => {
    if( === 200){
     resolve();
    }else{
     Toast()
    }
   },err => {
    reject(err);
    let message = 'The request failed!  Please check the network';
    if()message=;
    Toast(message)
   })
 })
}

export function del(url,data = {}){
 return new Promise((resolve,reject) => {
  (url,data)
   .then(response => {
    if( === 200){
     resolve();
    }else{
     Toast()
    }
   },err => {
    reject(err);
    let message = 'The request failed!  Please check the network';
    if()message=;
    Toast(message)
   })
 })
}

OK, edit the main file and then create a new file in the service and introduce the corresponding component method.

import Vue from 'vue';
import {post,fetch,patch,put,del,upload,ret2} from './index'
.$post=post;
.$fetch=fetch;
.$patch=patch;
.$put=put;
.$del=del;

Then you can start writing various API methods

//It can also not be neededconst _baseUrl=.API_URL;// Here I set the relative path in the project configuration file//Login methodconst loginURL = `${_baseUrl}api/admin/login`;
export const loginApi = function(json) {
 return .$post(loginURL,{"username":,"passwd":})
};
//Modify account information RESTfulconst editAdminUrl = `${_baseUrl}api/admin/user/info`;
export const editAdminListApi = function (id,json) {
 return .$put(`${editAdminUrl}/${id}`,json)
};
//etc....

Finally, it is used, which is very simple and convenient. It is introduced and used in vue files.

import { loginApi ,editAdminListApi } from "../../service/api";
  export default {
    methods:{
      //Log in      login(){
        let json = {
          userName:'xx',
          password:'xx'
        }
        loginApi().then(res=>{
          (res)
        })
      },
      // RESTful modification information      editAdminList(){
        let id = 1;
        let json = {name:11};
        editAdminListApi(id,json).then(res=>{
          (res)
        })
      }
    }
  }

Easy to use.

The above is a detailed explanation and integration of the use and packaging of axios in vue introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!