Introduction: As the mobile terminal business of the company is becoming less and less, most of the work is done on the Web terminal. Since I have taught myself a little BIT about HTML5 before, I plan to learn the web for real this time. Of course I preferred VUE. This article is about my use of axios encapsulation in Vue.

The first step, of course, is to install axios and reference it. That’s not what we’re talking about.

The first is our interface document api.js

Here I create a new service folder, a new api.js file, and I just define the URL and request method. The api.js method is as follows:

const CONTACT_API = {

    // Get the first news address
    getHomeList: {
        method: 'get',
        url: '/brainofficial/news/getNewsPage'
    }
    
}

export default CONTACT_API
Copy the code


The second step is to encapsulate http.js with web requests

http.js

import axios from 'axios'
import service from '.. /service/index.js'


// Set baseURL and the timeout period
let instance = axios.create({
    baseURL: 'https://www.suiren.com',
    timeout: 10000
})


// Define the container that wraps the request method
const Http = {}

// Loop through the API document and assign each method to Http
for (let key in service) {
    // The variable API is equivalent to the getHomeList object, which contains the URL and method
    let api = service[key]
    // Assign methods to Http (async is used so that two methods may be requested, and method 2 will be requested after method 1 has finished)
    Http[key] = async function Params,// The argument to pass isFormData =false// Form or JSON upload) {
        
        // Request a url
        let url = api.url
        
        // Define the axios config configuration parameters
        let config = {}
        let newParams = {}

        // Determine if the Content-Type is a form and should be concatenated to the URL
        if (params && isFormData) {// Convert the parameters if they are in form format
            newParams = new FormData()
            for (let i in params) {
                newParams.append(i, params[i])
            }
        } else {
            newParams = params
        }

        let response = {}
        if (api.method === 'put' || api.method === 'post' || api.method === 'patch') {
            try {
                response = await instance[api.method](api.url, newParams, config)
            } catch (error) {
                response = error
            }

        } else if (api.method === 'delete' || api.method === 'get') {
            config.params = newParams
    
            try {
                response = await instance[api.method](api.url, config)
            } catch (error) {
                response = error
            }
        }

        return response// Returns the response value}}// Add interceptors
instance.interceptors.request.use(config => {
    // What to do before the request occurs (this is equivalent to the mobile to display the loading loop)
    return config
}, err => {
    // Request error (the front-end operation is to cancel the loading circle, and a pop-up message indicating a network exception)
    return Promise.reject(err)
})

// Response interceptor
instance.interceptors.response.use(res => {
    / / request succeeded (front-end approach is to cancel the loading circle) |
    return res.data
}, err => {
    // The request failed.
    return Promise.reject(err)
})




export default Http

Copy the code

Three, use,

Before we use it, we’ll mount it on our vue instance. Here I’m using vue3, in main.js as follows:

import Http from './service/http'

// Mount Http to vue instances
const app = createApp(App);
app.config.globalProperties.$Http = Http;
app.use(store).use(router).mount('#app')
Copy the code

Make network requests as follows:

    async getList(a) {
      var res = await this.$Http.getHomeList()
      console.log(res)
    }

Copy the code

Remember when we wrapped it we defined the parameters, we can pass the parameters and whether it’s a form or not, and if nothing is passed here, then it represents the default values.

If a web page requires login, how to pass the token?

  • Method 1: You can add it via interceptors

  • Method 2: VuEX is directly used to store tokens, and the tokens are added when the value is determined during encapsulation

  • Method 3: Of course, we can also use the pass parameter sky boundary, such as:

      async getList(a) {
      var res = await this.$Http.getHomeList({value:xxx})
      console.log(res)
    }
Copy the code

So in the package http.js

        let config = {
            headers:{
                token:""
            }
        }

config.headers.token = params.value
Copy the code

Conclusion:

Here is my beginner’s understanding of the encapsulation used by Axios in VUE. Axios is packaged in VUE and should be packaged and modified differently for each project. Those who have better suggestions are welcome to visit