Encapsulation of Axios and management of API interface in Vue

first of all we need to understand why we want to encapsulate API

  • here is mainly code reuse, encapsulation, call again, directly to call the line, save a lot of repeated code, greatly reduce the amount of code

followed by the encapsulation of the API

interacts with the background to retrieve data in vue projects. We usually use the axios library, which is a promise-based HTTP library that runs on the browser side and in node.js. It has many nice features, such as intercepting requests and responses, canceling requests, converting JSON, client-side defense XSRF, and so on.

if you’re not familiar with axios you can check out the axios website oh, honey!

I usually create a new folder in my project’s SRC directory, and then I create a new http.js and an api.js file. The HTTp.js file is used to encapsulate our AXIOS and APi.js files to manage our interfaces uniformly.

let’s take a look at the code in action, dear!

  • http.js code operation
import axios from 'axios';

//development是开发环境 production是生产环境

//这里是设置请求超时时间 时间为5秒(可以自己进行设置)
        config.headers={DeviceType:"H5"}	//在这里写的是H5
        return config;

export function get(url,params){
    return new Promise((resolve,reject)=>{

export function post(url,params){
    return new Promise((resolve,reject)=>{
  • API. Js code operation
import {get,post} from './http.js'

// 设置get或者post请求
export function getList(){
	return get('api/app/recommend/appIndex?')

export function getTeacherXiang(params){
	return post('api/app/teacher/mainCourse',params)

One of the advantages of

API interface management is that we have centralized the API. If we need to modify the interface later, we can directly find the corresponding modification in api.js, instead of going to every page to find our interface and then modify it again. The key is, in case of modification the quantity is quite big, specification GG. In addition, if we modify the interface directly in our business code, it is easy to touch our business code and cause unnecessary trouble.

friendly tip : in order to avoid careless mistakes, it is best to write comments for each interface.

  • use the encapsulated method

in the vue file

import { getBanner} from "../../api/api.js";

async mounted() {
    var data= await getBanner();

friendship tips : the person who wrote this blog is not true. If there are any mistakes, please kindly put forward

Read More: