Share a self-wrapped Axios network request

Main functions and advantages:

Manage all interfaces in one folder (api.js). And can support dynamic interface, that is, the interface defined in api.js file can be used :xx placeholder, according to the need to change dynamically. Dynamic interface writing mimics the dynamic routing of VUE. If you are not familiar with dynamic routing, please check out my article: VUE Routing In Detail (Params and Query).

1. Encapsulate the request:

  1. Start by creating the HTTP directory under the SRC directory. Continue to create api.js and index.js files in the HTTP directory.
  2. Then import the index.js file from the HTTP directory into main.js. Register the request as a global component.
  3. Paste the code required for the encapsulation below into the appropriate folder

2. Basic use:

GetUsers () {const {data} = await this.$HTTP ({url: 'users'})},Copy the code

3. Use of dynamic interface:

// Example: Delete a user
deleteUser() {
  const { data } = await this.$http({
    method: 'delete'.// Dynamic interface writing mimics vUE dynamic routing
    // Params carries dynamic parameters, where "attribute name" needs to correspond to :id in the API interface
    // Ensure that the key carrying the parameter is consistent with :xx in the API interface
    url: {
      // Name is the "attribute name" in the api.js interface.
      name: 'usersEdit'.params: {
        id: userinfo.id,
      },
    },
  })
},
Copy the code

4. Lack of:

A wrapped request can only use this.$HTTP (). Can’t this.$http.get() or this.$http.delete().

Because I felt that this.$HTTP () was enough, I didn’t do any more wrapping

Feel free to contact me if you have any better ideas

Here is the code required for encapsulation:

  • Api.js manages all interfaces
// The following interface addresses are defined according to the project
const API = {
  / / the base interface
  baseURL: 'http://127.0.0.1:8888/api/private/v1/'./ / user
  users: '/users'.// Modify and Delete user interfaces (dynamic interfaces)
  usersEdit: '/users/:id',}export default API
​
Copy the code
  • Index.js logic code
// Here is the main logic of request encapsulation, you can analyze and optimize it, if there is a better encapsulation method, please contact me Q: 2356924146
import axios from 'axios'
import API from './api.js'const instance = axios.create({
  baseURL: API.baseURL,
  timeout: '8000'.method: 'GET'
})
​
// Request interceptor
instance.interceptors.request.use(
  config= > {
    // Request blocking code is written here, usually used to load popovers, or tokens that need to be carried with each request
    console.log('Is requesting... ')
    // Request token carried
    config.headers.Authorization = sessionStorage.getItem('token')
    return config
  },
  err= > {
    console.log('Request failed', err)
  }
)
​
// Response interceptor
instance.interceptors.response.use(
  res= > {
    console.log('Response successful')
    // The return object is bound to the response object
    return res
  },
  err= > {
    console.log('Response failed', err)
  }
)
​
{method, url, params/data}
export default function(options = {}) {
  return instance({
    method: options.method,
    url: (function() {
      const URL = options.url
​
      if (typeof URL === 'object') {
        // Get the dynamic URL
        let DynamicURL = API[URL.name]
​
        // Replace the corresponding key in DynamicURL
        for (const key of Object.keys(URL.params)) {
          DynamicURL = DynamicURL.replace(':' + key, URL.params[key])
        }
​
        return DynamicURL
      } else {
        return API[URL]
      }
    })(),
    // Get the query string argument
    params: options.params,
    // Gets the request body string argument
    data: options.data
  })
}
​
Copy the code
  • Main.js registers the request as a global component
import Vue from 'vue'// The index.js file in the HTTP directory is automatically imported
import http from './http'
​
Vue.prototype.$http = http
Copy the code