How to encapsulate axios with vue!

Keywords: axios Vue network Mobile

How to package axios with vue

This project needs to add validation code before login. In order to facilitate the distinction between request interfaces, it can encapsulate two request interfaces, one is required before login, and the other is requested after login, so that they do not interfere with each other.
1. Set up a folder axios before login, where index.js writes the request interface and config.js writes the configuration.

index.js

/*Interface file*/
//axios configuration file
import index from './config'

export default {
    API_VERIFY: (params) => index('get', '/login/getverify?', params),//Verification Code

    API_LOGIN: (body ) => index('post','login/index?' ,body),//Sign in
   
}

 config.js

import axios from 'axios'
import index from './index'

const instance = axios.create({
    //Default address
    baseURL: 'http://192.168.10.26/v1',
    //Response time
    timeout: 6000
})

//request interceptor
instance.interceptors.request.use(
    /**
     * @param config    The incoming url and parameters
     */
    (config) => {
        axios.defaults.headers['Content-Type'] = 'Access-Control-Allow-Origin'
        // console.log("send request", config)
        return config
    },
    (error) => {
        console.log("Failed to send request")
        return Promise.reject(error)
    }
)

//Response interceptor
instance.interceptors.response.use(
    (response) => {
        // console.log("successful response")
        return response.data
    },
    (error) => {
        console.log("Response failure",error.response)
        return Promise.reject(error)
    }
)
/**
 * @param {Request mode} method 
 * @param {Request address} path 
 * @param {Request parameter} params
 */
export default function (method, url, params) {
    method = method.toLowerCase()
    switch (method) {
        case 'get':
            params = params || ''
            return instance.get(url + params)
        case 'post':
            params = params || null
            return instance.post(url,params)
        default:
        console.error('Unknown method:'+method)
        return false
    }
}

2. Set up a folder request after login, where api.js writes the request interface and http.js writes the configuration

http.js

import axios from 'axios'
import router from 'vue-router'
import {
  Loading,
  Message
} from 'element-ui'
var instance = axios.create({
  baseURL: 'http://192.168.10.26/v1',
  timeout: 6000,
})
var access_token = localStorage.getItem("token");
// Add request interceptor
instance.interceptors.request.use(function (config) {
  // What to do before sending a request?
  access_token = localStorage.getItem("token");
  // console.log(access_token)
  if (access_token) {
    config.headers.Authorization = `${access_token}`;
  }  
    return config;
}, function (error) {
  // What to do with request error?
  return Promise.reject(error);
});
 
// http request interceptor
var loadinginstace = "";
instance.interceptors.request.use(config => {
  loadinginstace = Loading.service({
    fullscreen: true
  })
  return config
}, error => {
  loadinginstace.close();
  Message.error({
    message: 'Load timeout'
  })
  return Promise.reject(error);
})
// http response interceptor
instance.interceptors.response.use(data => { // Response successfully closes loading
  loadinginstace.close();
  //  console.log(data)
  return data
}, error => {
  const {
    code
  } = error;
  if (code == 'ECONNABORTED') {
    loadinginstace.close();
    Message.error({
      message: 'Network timeout, please re-request'
    })
    return Promise.reject(error);
  }
  const {
    status
  } = error.response; //There is a status in response. We deconstruct it in es6
  if (status == 401) {
    //Background definition 401 is token expiration
    // alert('Please log in again!');
    loadinginstace.close();
    //  If token expires; we should clear token
    localStorage.removeItem("token");
    localStorage.removeItem("nickname");
    localStorage.removeItem("avatarImg");
    localStorage.removeItem("mobile");
    //   Clear and jump to the login page
    location.href = "/Login";
  } else {
    alert('The system is busy!');
  }
  
  loadinginstace.close();
  Message.error({
    message: 'Failed to load'
  })
  return Promise.reject(error)
})

export const get = (url, query) => {
  query = query || '';
  return instance.get(url + query)
}
export const post = (url, query) => {
  return instance.post(url, query)
}

api.js

import { get, post } from './http'

export default {
    GET_GRADES:(obj)=>get('/schoolcls/getgrades?',obj),
    
    CLASS_MANAGE:(query,body)=>post('/schoolcls/index?'+query,body),
 
} 
 
 

3. Introduce in main.js

import api from './request/api'
import index from './axios/index'

Vue.prototype.$api = api
Vue.prototype.$index = index

4. Call on a page that requires a request interface

(1) before login

For example: login.js

//Before login
submitForm(){

 this.$index.API_LOGIN(obj).then(res=>{
console.log(res)
}).catch(err=>{
console.log(err);
})

}

(2) after login

For example: one of the post-login pages

//Post-login sub-pages
getdata(){
this.$api.GET_GRADES().then(res=>{
console.log(res);
}).catch(err=>{
console.log(err);
})
}

Actual combat conclusion, please do not write well, please do not hesitate to comment. Thank you!

Posted by atitthaker on Sun, 06 Oct 2019 23:09:09 -0700