Step 1: Configure AxiOS

First, create a service.js that holds axiOS configuration, interceptors, etc., and finally export an AXIos object. I usually use elementUI a lot, but you can use your own UI library here.

import axios from 'axios'
import { Message, Loading } from 'element-ui'
const ConfigBaseURL = 'https://localhost:3000/'// The default path, where env can also be used to determine the environmentletLoadingInstance = null // in this case loading // creates an axiOS instance using the create methodexportConst Service = axios.create({timeout: 7000, // request timeout time baseURL: ConfigBaseURL, method:'post',
  headers: {
    'Content-Type': 'application/json; charset=UTF-8'}}) / / add request interceptor Service. The interceptors. Request. Use (config = > {loadingInstance = Loading. Service ({the lock:true,
    text: 'loading... '
  })
  returnConfig}) / / add the response interceptor Service. The interceptors. Response. Use (response = > {loadingInstance. With close () / / the console. The log (response)return response.data
}, error => {
  console.log('TCL: error', error) const msg = error.Message ! == undefined ? error.Message :' '
  Message({
    message: 'Network error' + msg,
    type: 'error',
    duration: 3 * 1000
  })
  loadingInstance.close()
  return Promise.reject(error)
})
Copy the code

The specific interceptor logic depends on the specific business. I have no logic here, just added a global loading

Step 2: Encapsulate the request. Here I create another request.js, which contains the specific request.

export function getConfigsByProductId(productId) {
  return Service({
    url: '/manager/getConfigsByProductId',
    params: { productId: productId }
  })
}
export function getAllAndroidPlugins() {
  return Service({
    url: '/manager/getAndroidPlugin ',
    method: 'get'})}export function addNewAndroidPlugin(data) {
  return Service({
    url: '/manager/addAndroidPlguin',
    data: JSON.stringify(data)
  })
}
Copy the code

Of course, you can wrap the URL again and put it in another file, which I don’t think makes sense and adds complexity. The main attention here is the naming problem. It is recommended to name by function, for example, I request method + function or content + parameter, so that the name getConfigsByProductId is also clear

Step 3: Use

In the VUE component

import {getAllAndroidPlugins,getConfigsByProductId,addNewAndroidPlugin} from '@/api/request.js'

getAllAndroidPlugins()
.then(res=>{
})
Copy the code

It is used globally in main.js

import {Service} from '@/api/Service.js'
Vue.prototype.$axios=ServiceCopy the code