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!

Js
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
//第一步:引入axios 
import axios from 'axios';

//在这里设置开发环境和生产环境的默认路径
//development是开发环境 production是生产环境
if(process.env.NODE_ENV=='development'){
    axios.defaults.baseURL='http://120.53.31.103:84/api/app/'
}
if(process.env.NODE_ENV=='production'){
    axios.defaults.baseURL='https://wap.365msmk.com'
}

//这里是设置请求超时时间 时间为5秒(可以自己进行设置)
axios.defaults.timeout=5000;
//在请求拦截可以设置权限 
//如果不设置数据会请求失败或为空数据,在这里也可以用来判断token
axios.interceptors.request.use(
    config=>{
        config.headers={DeviceType:"H5"}	//在这里写的是H5
        return config;
    }
)

//封装get请求
export function get(url,params){
    return new Promise((resolve,reject)=>{
        axios.get(url,{
            params:params
        }).then(res=>{
            resolve(res)
        }).catch(err=>{
            reject(err)
        })
    })
}

//封装post请求
export function post(url,params){
    return new Promise((resolve,reject)=>{
        axios.post(url,
         params
        ).then(res=>{
            resolve(res.data)
        }).catch(err=>{
            reject(err.data)
        })
    })
}
  • API. Js code operation
//引入http.js
import {get,post} from './http.js'

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

//讲师详情的主讲课程
//在里面可以传递id,参数等
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();
  //获取完数据就可以直接打印出来了
    console.log(data);
}

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

Read More: