Recently, when using VUE to reconstruct the m station of the company, AXIos was used for data request. Due to the needs of the project, a secondary encapsulation was performed on AXIos.Click to go to Axios

/ / introduce axios
import axios from 'axios'

let cancel ,promiseArr = {}
const CancelToken = axios.CancelToken;
// Request interceptor
axios.interceptors.request.use(config= > {
    // Cancels the same request that is currently in progress
    if (promiseArr[config.url]) {
        promiseArr[config.url]('Operation cancel')
        promiseArr[config.url] = cancel
    } else {
        promiseArr[config.url] = cancel
    }
      return config
}, error => {
    return Promise.reject(error)
})

// Response interceptor is exception handling
axios.interceptors.response.use(response= > {
    return response
}, error => {
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = 'Error request'
          break;
        case 401:
          error.message = 'Not authorized, please log in again'
          break;
        case 403:
          error.message = 'Access denied'
          break;
        case 404:
          error.message = 'Request error, resource not found'
          break;
        case 405:
          error.message = 'Requested method not allowed'
          break;
        case 408:
          error.message = 'Request timed out'
          break;
        case 500:
          error.message = 'Server side error'
          break;
        case 501:
          error.message = 'Network not implemented'
          break;
        case 502:
          error.message = 'Network error'
          break;
        case 503:
          error.message = 'Service unavailable'
          break;
        case 504:
          error.message = 'Network timeout'
          break;
        case 505:
          error.message = 'The HTTP version does not support this request'
          break;
        default:
          error.message = 'Connection error${error.response.status}`}}else {
      error.message = "Failed to connect to server"
    }
    message.error(error)
  	return Promise.resolve(error.response)
})

axios.defaults.baseURL = '/api'
// Set the default request header
axios.defaults.headers = {
    'X-Requested-With': 'XMLHttpRequest'
}
axios.defaults.timeout = 10000

export default {
  / / get request
    get (url,param) {
      return new Promise((resolve,reject) = > {
        axios({
          method: 'get',
          url,
          params: param,
          cancelToken: new CancelToken(c= > {
            cancel = c
          })
        }).then(res= > {
          resolve(res)
        })
      })
    },
  / / post request
    post (url,param) {
      return new Promise((resolve,reject) = > {
        axios({
          method: 'post',
          url,
          data: param,
          cancelToken: new CancelToken(c= > {
            cancel = c
          })
        }).then(res= > {
          resolve(res)
        })
      })
     }
  }
Copy the code

instructions

  1. To prevent the same request that is currently being processed when a request is initiated, hash judgment is added to the request interceptor to intercept the same request URL
  2. Remove the get and POST common configuration from axios
    axios.defaults.baseURL = '/api'// Set the default request header axios.defaults.headers = {'X-Requested-With': 'XMLHttpRequest'
    }
    axios.defaults.timeout = 10000
    Copy the code
  3. Wrapping the GET and POST request So you might ask, well, this is axios returning the promise object, so why wrap the promise for GET and POST again? For my part, using async await in development will cause the data request to fail, and the error is that the promise object is not returned. Async await returns a promise object to avoid the above error. Here is an example of a request interface
import req from '.. /api/requestType'/** * Tour details */export const groupDetail = param => {
    return req.get('/RestHome/GroupDetail',param)
}
Copy the code

The following is the data acquisition

async getData() {
    const params = {
        TopCataID: 0,
        pageNumber: this.pageNumber,
        pageSize: this.pageSize
    }
    const res = await groupList(params)
},
Copy the code
  1. Common errors in requests are handled globally in the corresponding interceptor
axios.interceptors.response.use(response => {...
Copy the code

At this point, we’ve simply encapsulated axios for our project