Encapsulating Axios in Vue cli 3.0 +

Time:2020-12-2

In the previous project, the request API and request mode are encapsulated. The encapsulation is for simple and better management of the interface given by the back-end, the reusability of the request code and the simplification of the code.

Installing Axios

   $ npm install axios

Create a catalog file

  1. Create HTTP directory in SRC
  2. Create in HTTP directory http.js How users request
  3. Create in HTTP directory api.js It is used to store the back end and provide interface
  4. Create in HTTP directory axios.js Users do Axios interceptor
  5. Create it under the root directory vue.config.js User request agent configuration

The next is the code

Project / SCR / HTTP/ http.js Chinese code

import axios from 'axios';

export default {
    /**
     *Get request
     *@ param URL interface routing
     *Does @ param auth need to bring login information
     * @returns {AxiosPromise<any>}
     */
    get(url, auth = false) {
        if (auth) {
            return axios.get(url, {headers: {Authorization: 'Your back-end user authenticates information'}});
        } else {
            return axios.get(url);
        }
    },

    /**
     *Post request
     *
     *@ param URL interface routing
     *@ param data interface parameters
     *Does @ param auth need to bring login information
     * @returns {AxiosPromise<any>}
     */
    post(url, data, auth = false) {
        if (auth) {
            return axios.post(url, data, {headers: {Authorization: 'Your back-end user authenticates information'}});
        } else {
            return axios.post(url, data);
        }
    },

    /**
     *Put request
     *@ param URL interface routing
     *@ param data interface parameters
     *Does @ param auth need to bring login information
     * @returns {AxiosPromise<any>}
     */
    put(url, data, auth = false) {
        if (auth) {
            return axios.put(url, data, {headers: {Authorization: 'Your back-end user authenticates information'}});
        } else {
            return axios.put(url, data);
        }
    },

    /**
     *Delete
     *@ param URL interface routing
     *Does @ param auth need to bring login information
     * @returns {AxiosPromise}
     */
    del(url, auth = false) {
        if (auth) {
            return axios.delete(url, {headers: {Authorization: 'Your back-end user authenticates information'}});
        } else {
            return axios.delete(url);
        }
    },

    /**
     *Upload files
     *@ param URL interface routing
     *@ param file interface file
     *Does @ param auth need to bring login information
     */
    uploader(url, file, auth = false) {
        let param = new FormData();
        param.append('file', file)
        if (auth) {
            return axios.post(url, param, {headers: {Authorization: 'Your back-end user authenticates information'}})
        } else {
            return axios.post(url, param)
        }
    },
}

You can create a file API under project / SCR / HTTP /, and then create interface files based on project modules to facilitate management

Project / SCR / HTTP/ api.js code

import Goods from './api/goods.js';

export default {
    //Home page
    Index: {
        index: '/index/index'
    },

    //Personal Center
    Home: {
        UserInfo: '/user/info'
    },

    //Of course, it can also be managed by file
    Goods: Goods

}

Project / SCR / HTTP / API/ goods.js Chinese code

export default {
    GoodsShow: '/goods/default'
}

Project / SCR / HTTP/ axios.js Chinese code

import axios from 'axios';

//Request interception
axios.interceptors.request.use(config => {
    //1. This location is the last configuration before request
  //2. Of course, you can also add the user authorization information required by your backend in this location
  return config
}, error => {
    return Promise.reject(error)
})

//Response interception
axios.interceptors.response.use(response => {
  //Request successful
  //1. Customize your interception according to your own project requirements
  //2. Then return the data
  return response;
}, error => {
    //Request failed
      if (error && error.response) {
            switch (error.response.status) {
                case 400:
                    //Your handling of 400 errors\
                break
                case 401:
                    //Handling 401 errors
                break
                default:
                //If none of the above is handled
                return Promise.reject(error);
          }
    }

})

It’s ready. So the next step is project / SCR/ min.js Add code in

Project / SCR/ min.js Chinese code

import Vue from 'vue';
import App from './App.vue';
import api from './http/api';
import http from './http/http';

//Interceptors
import './http/axios'

//Global registration of back-end interfaces
Vue.prototype.$api = api;
//Global registration of request mode
Vue.prototype.$http = http;

So the next step is to use it

Project / SRC / views / index/ index.vue We use it

<template>
     <div>
     </div>
 </template>

<script>
  export default {
        name: "Index",
        mounted() {
            this.handle()
        },
        methods: {
            handle(){
                //Of course, if you need to bring login information to request, this interface can follow true or false after the route to determine whether to bring login information when requesting
                //We encapsulate a request in this way.
               this.$http.get(this.$api.Index.index,true).then((result) => {
               })
            }
        }
    }
</script>

<style scoped>

</style>

Next is the agent configuration

Project/ vue.config.js code

//Please note that [he will get different env files according to your environment]
const target = process.env.APP_API_URL;

module.exports = {
  devServer: {
    //All interface request proxies
  proxy: {
      '/api': {
        target: target,
        changeOrigin: true,
        ws: true,
        pathRewrite: {
              '^api': ''
        }
      }
    }
  }
}

Please refer to Env file differenceshttps://cli.vuejs.org/zh/guide/mode-and-en…Environment variable pattern

The above is my personal summary, I have some Vue technology. I hope you can give different opinions. Comments are welcome

This work adoptsCC agreementThe author and the link to this article must be indicated in the reprint

Recommended Today

15. How to rank the scores of millions of candidates

How to rank the scores of millions of candidates Focus on “code brother byte”. Here are algorithm series, big data storage series, spring series, source code architecture disassembly series, interview series Coming soon. Don’t get lost by setting star In fact, counting sort is a special case of bucket sort. Bucket sortingThe core idea is […]