SoFunction
Updated on 2025-04-04

Complete steps to manage Vue encapsulation Axios and API interfaces

1. Preface

The unified management of Axios' encapsulation and API interface is actually the main purpose of helping us simplify code and facilitate later updates and maintenance.

2. Axios packaging steps

Installation: npm install axios -S

Generally, I will create a new network folder in the project's src directory, as our network request module, and then create a new one and a file and one in it. Files are used to encapsulate our axios, to manage our interface urls, and to expose the API methods we placed.

// Introduce axios inimport axios from 'axios'; // Introduce axiosimport router from '../router';
// Vant's toast prompt box component, you can change it according to your ui component.import { Toast } from 'vant'; 
 

Our project environments may include a development environment, a test environment, and a production environment. We match our default interface url prefix through node's environment variables. I won't say much about axios' default request address.

Create a config directory.

Create ++ in the directory

content:

={
    baseUrl:' :4456' //Baseurl used in the development environment}

Set request timeout

Set the default request timeout time. For example, if it exceeds 10 seconds, the user will be informed that the current request timeout, please refresh, etc.

// Switching environmentconst {baseUrl}=require('../config/env.'+.NODE_ENV);
 
// At the same time, scripts need to specify the mode of the test environment --mode test "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "test": "vue-cli-service build --mode test",
    "lint": "vue-cli-service lint"
  }
 
const service = ({
  baseURL: baseUrl, // url = base api url + request url
  withCredentials: false, // send cookies when cross-domain requests
  timeout: 1000*12 // Request timeout})

Settings of post request header

When requesting post, we need to add a request header, so we can make a default setting here, that is, set the request header of post to application/x-www-form-urlencoded;charset=UTF-8

// Set post request header['Content-Type'] = 'application/x-www-form-urlencoded';

Request for interception

We can intercept a request before sending a request. Why do we intercept the request? What are we used to intercept the request? For example, some requests require the user to log in before accessing, or when posting, we need to serialize the data we submitted. At this time, we can perform an intercept before the request is sent to perform the operation we want.

// Import vuex first, because we want to use the state object inside// The path of vuex is written according to its own pathimport store from '@/store/index';
 
// Request an interceptor(
  config => {
    // Not passing loading is enabled by default    if (!) {
      // Whether to enable loading      ({
        forbidClick: true
      })
    }
      // Check whether there is a token in vuex before sending a request        // If it exists, add tokens to the header requested by http, so that the background judges your login situation based on the token        // Even if there is a token locally, it is possible that the token is expired, so the return status must be judged in the response interceptor    if () {
       = ;
      //Some interfaces are = token    }
    return config
  },
  error => {
    // do something with request error
    (error) // for debug
    return (error)
  }
)

Let’s talk about tokens here. Generally, after logging in, the user’s token is stored locally through localStorage or cookie. Then, every time the user enters the page (that is, in), he will first read the token from the local storage. If the token exists, it means that the user has logged in, and the token status in vuex is updated. Then, every time you request an interface, you will carry a token in the requested header. The backend staff can judge whether your login has expired based on the token you carry. If you don’t carry it, it means you have not logged in. At this time, some friends may have questions, that is, each request carries a token, so what if a page can be accessed without the user login? In fact, your front-end request can carry a token, but the background can choose not to receive it.

Response to intercept

// Response Interceptor(
    response => {   
        // If the returned status code is 200, it means that the interface request is successful and the data can be obtained normally        // Otherwise, an error will be thrown        if ( === 200) {            
            return (response);        
        } else {            
            return (response);        
        }    
    },    
    // If the server status code does not start with 2    // Here you can negotiate a unified error status code with your backend developers    // Then perform some operations based on the returned status code, such as login expiration prompt, error prompt, etc.    // Here are a few common operations, and other requirements can be expanded by themselves    error => {            
        if () {            
            switch () {                
                // 401: Not logged in                // If you are not logged in, jump to the login page and carry the path to the current page                // Return to the current page after logging in successfully. This step requires operation on the login page.                case 401:                    
                    ({                        
                        path: '/login',                        
                        query: { 
                            redirect:  
                        }
                    });
                    break;
 
                // 403 token expires                // Prompt the user when login expires                // Clear local tokens and clear token objects in vuex                // Jump to login page                case 403:
                     Toast({
                        message: 'Login expires, please log in again',
                        duration: 1000,
                        forbidClick: true
                    });
                    // Clear token                  ('FedLogOut').then(() => {
                    // Jump to the login page and pass the fullPath page you want to browse. After logging in successfully, jump to the page you need to access                 ({                            
                            path: '/login',                            
                            query: { 
                                redirect: 
                            }      
                  })      })       
                    break; 
 
                // The 404 request does not exist                case 404:
                    Toast({
                        message: 'Network request does not exist',
                        duration: 1500,
                        forbidClick: true
                    });
                    break;
                // Other errors, directly throw an error message                default:
                    Toast({
                        message: ,
                        duration: 1500,
                        forbidClick: true
                    });
            }
            return ();
        }else {
            // Handle the situation of disconnection            // eg: When the request timeout or the network is disconnected, update the network status of the state.            // The network state controls the display of a global outage prompt component to hide            // Regarding the refresh and re-acquisition of data in the disconnected network component, it will be explained in the disconnected network component            ('changeNetwork', false);
        }
 
    
});
 
//The last instance is exportedexport default service;

3. Unified management of API interfaces

A new API folder has been created, with one and multiple interface js files divided according to the module. It is the exit of an API, and other JS is used to manage the interfaces of each module.

For example, the following:

/**
  * article module interface list
  */
 
import request from '@/network/http'; // Import the axios instance created in httpimport qs from 'qs'; // Whether to import the qs module according to requirements 
const article = {    
    // News list    articleList () {        
       return request({
       url: '/artical',
       method: 'get',
       params,
       hideloading: false //Set not to hide loading loading    })  
    },    
    // News details, demonstration    articleDetail (id, params) {        
         return request({
              url: '/detail',
              method: 'get',
              params:{
                goodsId
              },
              hideloading: true
            })
    },
    // Post Submit    login (data) {        
      return request({
      url:'/adduser',
      method:'post',
      data:(data), //Note that the data parameters are used for post submission      hideloading: true
 
     })   
    }
    // Other interfaces………}
 
export default article;

Code

/**
  * Unified export of API interface
  */
// Article module interfaceimport article from '@/api/article';
// Interfaces to other modules... 
// Export interfaceexport default {    
    article,
    // ……
}
 
Use in components(Import on demand)
import {article} from '@/api/index'
 
created(){
   ().then(info=>{
       if(==200)
     =
  }
     })
}

mount the API to the top to avoid the steps to introduce

In order to facilitate the call of the API, we need to mount it to the prototype of vue. In

import Vue from 'vue'
import App from './App'
import router from './router' // Import routing filesimport store from './store' // Import vuex fileimport api from './api' // Import the API interface 
.$api = api; // mount the api to the prototype of vue to copy the code

Then we can use it in the component

//No import requiredmethods: {    
    onLoad(id) {      
        this.$(id, {        
            api: 123      
        }).then(res=> {
            // Perform certain operations        })    
    }  
}
 
 
Deal with disconnection
<template>  
    <div >    
        <div v-if="!network">      
            <h3>I'm out of the internet</h3>      
            <div @click="onRefresh">refresh</div>      
        </div>    
        <router-view/>      
    </div>
</template>
 
<script>
    import { mapState } from 'vuex';
    export default {  
        name: 'App',  
        computed: {    
            ...mapState(['network'])  
        },  
        methods: {    
            // The purpose of refreshing the current page data by jumping an empty page and returning it            onRefresh () {      
                this.$('/refresh')    
            }  
        }
    }
</script>
 
// 
beforeRouteEnter (to, from, next) {
    next(vm => {            
        vm.$()        
    })    
}

Summarize

This is the end of this article about Vue encapsulation Axios and API interface management. For more related content on Vue encapsulation Axios and API interfaces, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!