Vue cli 3.0 + package for Axios

Time:2021-9-26

In the front-end project, the request API and request mode are encapsulated. The encapsulation is to simplify and better manage the interface given by the back-end, reuse the request code and simplify the code.

Installing Axios

   $ npm install axios

Create catalog file

  1. Create HTTP directory in SRC
  2. How to create http.js user requests in the HTTP directory
  3. Create api.js in the HTTP directory to store the interfaces provided by the backend
  4. Create axios.js in the HTTP directory and make the user an Axios interceptor
  5. Create vue.config.js user request agent configuration under the root directory

Next is the code

Code in project / SCR / HTTP / http.js

import axios from 'axios';

export default {
    /**
     *Get request
     *@ param URL interface routing
     *@ param auth do you 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
     *@ param auth do you 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
     *@ param auth do you 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
     *@ param auth do you 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 file
     *@ param URL interface routing
     *@ param file interface file
     *@ param auth do you 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 the project / SCR / HTTP /, and then create an interface file according to the project module in the API to facilitate management

Project / SCR / HTTP / api.js code

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

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

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

    //Of course, it can also be managed in the form of files
    Goods: Goods

}

Code in project / SCR / HTTP / API / goods.js

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

Code in project / SCR / HTTP / axios.js

import axios from 'axios';

//Request interception
axios.interceptors.request.use(config => {
    //1. This location is the last configuration before the 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 succeeded
  //1. Customize your own interceptor according to your project needs
  //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:
                    //Handle 401 errors
                break
                default:
                //If none of the above is the treatment of
                return Promise.reject(error);
          }
    }

})

It’s ready. Then the next step is to add code to the project / SCR / min.js

Code in project / SCR / min.js

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

//Axios interceptor
import './http/axios'

//Global registration of backend interfaces
Vue.prototype.$api = api;
//Global registration of request mode
Vue.prototype.$http = http;

Then the next step is to use

We use it in the project / SRC / views / index / index.vue

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

<script>
  export default {
        name: "Index",
        mounted() {
            this.handle()
        },
        methods: {
            handle(){
                //Of course, if you need to request this interface with login information, you can follow the route with true or false to decide 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

//Back end request address note [it will get different env files according to your environment]
const target = process.env.APP_API_URL;

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

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


vue

This work adoptsCC agreement, reprint must indicate the author and the link to this article

You’re far from it!

Recommended Today

A detailed explanation of the differences between Perl and strawberry Perl and ActivePerl

Perl is the abbreviation of practical extraction and report language “practical report extraction language”. Application of activestateperl and strawberry PERL on Windows platformcompiler。 Perl   The relationship between the latter two is that C language and Linux system have their own GCC. The biggest difference between activestate Perl and strawberry Perl is that strawberry Perl […]