How does axios encapsulate the request?

this.$axios.get("/collection/select",{
    params:{
        schoolUid:this.common.getLocal("roleId"),
        name:"",
        pageNum:0,
        pageSize:0
    }
})
.then(res=>{
    if(res.data.code == 1){
        this.list_plan = res.data.data.list;
    }
})

this request is used on a lot of pages, and it"s tiring to write it this way every time.
and the parameters are all written to death, so all I care about is the return value. How to encapsulate it?

Mar.21,2022

personally, it is not recommended that you send a request in this way. I hope you can read on, a relatively simple

you should be like this.

A method axios.js that separately encapsulates an axios request contains the post,get,fromdate request method.

// axios.js 
import axios from 'axios';
import Cookies from 'js-cookie';

axios.defaults.timeout = 9999999;
axios.defaults.baseURL ='';


//http request 
axios.interceptors.request.use(
  config => {
    let token = Cookies.get('token'); //cookiejs-cookie
    
    if(config.method=='post'){ // post token
        config.data = config.data;
        if(token){
          config.data.token = token
        } 
        // else {
        //   console.log('token')
        // }
        config.headers = {
        'Content-Type':'application/x-www-form-urlencoded',
        }
    } else if(config.method=='get'){ // get url
        config.params.token = token
        config.headers = {
            'Content-Type':'application/x-www-form-urlencoded',
        }
    }
    return config;
  },
  error => {
    return Promise.reject(err);
  }
);


//http response 
axios.interceptors.response.use(
    // token 
  response => {
    if(response.data.errCode ==2){
      router.push({
        path:"/login",
        querry:{redirect:router.currentRoute.fullPath}//
      })
    }
    return response;
  },
  error => {
    return Promise.reject(error)
  }
)


/**
 * get
 * @param url
 * @param data
 * @returns {Promise}
 */
export function get(url,params={}){
  return new Promise((resolve,reject) => {
    axios({
        url: url,
        method: 'GET',
        params: params,
        transformRequest: [function (data) {
          let ret = ''
          for (let it in data) {
            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
          }
          return ret
        }],
        })
        .then(res => {
            if(res.data.code == 1001){
                this.$Message.warning(',' + res.data.message);
                this.$router.push({path:'/'})
                return
            }
            resolve(res.data);
        })
        .catch(err => {
            reject(err)
        })
  })
}


/**
 * post
 * @param url
 * @param data
 * @returns {Promise}
 */
 export function post(url,data = {}){
   return new Promise((resolve,reject) => {
        axios({
        url: url,
        method: 'POST',
        data: data,
        transformRequest: [function (data) {
          let ret = ''
          for (let it in data) {
            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
          }
          return ret
        }],
        })
        .then(res => {
            if(res.data.code == 1001){
                this.$Message.warning('' + res.data.message);
                this.$router.push({path:'/'})
                return
            }
            resolve(res.data);
        })
        .catch(err => {
            reject(err)
        })
   })
 }

 /**
  * from 
  */
 export function get_from(URL, PARAMS) {
  var p = new Promise((resolve, reject) =>{        //
    var temp = document.createElement("form");
    temp.action = URL;
    temp.method = "get";
    temp.style.display = "none";
    for (var x in PARAMS) {
      var opt = document.createElement("textarea");
      opt.name = x;
      opt.value = PARAMS[x];
      temp.appendChild(opt);
    }
    document.body.appendChild(temp);
    temp.submit();
    this.$Loading.finish();
    resolve(temp) 
  });
  return p;
}

/**
 *  excel
 */

export function up_excel(URL, PARAMS) {
  return new Promise((resolve,reject) => {
    let token = this.$Cookies.get('token')
    let config = {
        headers: {
        'Content-Type': 'multipart/form-data'
        }
    }
    PARAMS.append('token', token)

    axios.post(URL, PARAMS, config)
      .then( res => {
        resolve(res.data)
      })
      .catch(err=>{
        reject(err)
      })
  })
}

then expose the methods in axios.js in main.vue. Then register globally for use (as below)

import {post,get,get_from,up_excel} from './api/axios'
Vue.prototype.$get=get;
Vue.prototype.$get_from = get_from;
Vue.prototype.$up_excel = up_excel;

at this point, you can use it again in the component. The methods used are as follows

// url:   data:
this.$post(url,data)
    .then(res=>{
        if(res.code == 200){
            // 
        } else {
            // 
        }
    })
    
 this.$get(url,data)
    .then(res=>{
        if(res.code == 200){
            // 
        } else {
            // 
        }
    })
   

ps: I personally like to put the whole interface in a file like this linkUrl.js

let main = ''

const linkurl = {
    login : main + '/login/login',
}

export default linkurl

then register globally

import linkurl from './api/LinkUrl'

Vue.prototype.$linkurl = linkurl

at this time, you can use this directly in the encapsulated request

this.$post(this.$linkurl.login, data)  // this.$linkurl.loginjs
    .then(res=>{
        if(res.code == 200){
            // 
        } else {
            // 
        }
    })
    

for example, write a public Js, encapsulation method in the api folder, and you can introduce import when you need it


  http://sfau.lt/b51Tv8

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3f036-2c457.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3f036-2c457.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?