Everyday Vue development projects always need to wrap AXIos, so today I can write a complete AXIOS package, combined with the hints of the ElementUI component library, which is quite useful.

Without further ado, the code posted below, if there are incorrect places, welcome to correct:

import axios from 'axios'

// Message is imported on demand, similar to VantUI, depending on your needs
import { Message } from 'element-ui'

Error code message box
const tip = message= > {
  Message({
    message,
    duration: 1000.type: 'error'})}// Error code capture
const errorHandler = (status) = > {
  switch (status) {
    case 302:
      tip('Interface Redirection')
      break

    case 400:
      tip('Request error')
      break

    case 401:
      tip('Not authorized, please log in again')
      break

    case 403:
      tip('No operation permission')
      break

    case 404:
      tip('Error requesting address')
      break

    case 405:
      tip('Requested method not allowed')
      break

    case 408:
      tip('Request timed out')
      break

    case 422:
      tip('Unmanageable entity')
      break

    case 500:
      tip('Server error')
      break

    case 501:
      tip('Service not implemented')
      break

    case 502:
      tip('Gateway error')
      break

    case 503:
      tip('Service unavailable')
      break

    case 504:
      tip('Service temporarily unavailable, please try again later')
      break

    case 505:
      tip('HTTP version not supported ')
      break

    default:
      tip('System error, please try again later')
      break}}// Intercepts duplicate requests
// Repeated requests refer to requests with the same mode, path, and parameters
const pendingMap = new Map(a)// Generate unique keys for each request
function getPendingKey (config) {
  let { url, method, params, data } = config
  if (typeof data === 'string') {
    data = JSON.parse(data)
  }
  return [url, method, JSON.stringify(params), JSON.stringify(data)].join('&')}// Store a unique value for each request
function addPendingKey (config) {
  const pendingKey = getPendingKey(config)
  config.cancelToken = config.cancelToken || new axios.CancelToken((cancel) = > {
    if(! pendingMap.has(pendingKey)) { pendingMap.set(pendingKey, cancel) } }) }// Retrieve the duplicate request and delete it
function removePendingKey (config) {
  const pendingKey = getPendingKey(config)
  if (pendingMap.has(pendingKey)) {
    const cancelToken = pendingMap.get(pendingKey)
    cancelToken(pendingKey)
    pendingMap.delete(pendingKey)
  }
}

class HttpRequest {
  // Set the base path
  constructor (baseURL) {
    this.baseURL = baseURL
  }

  // Set the instance configuration of axios
  getInstanceConfig () {
    const config = {
      timeout: 10000.baseURL: this.baseURL,
      headers: {
        'Content-Type': 'application/json; charset=utf-8'}}return config
  }

  // Set interceptor
  interceptors (instance) {
    // Request interceptor
    instance.interceptors.request.use(config= > {
      removePendingKey(config)
      addPendingKey(config)
      // The token is obtained by the user after login
      const token = 'jxnwejjwsnwjswswxwxdw'
      token && (config.headers.Authorization = `Bear ${token}`)
      return config
    }, error= > {
      Promise.reject(error)
    })

    // Response interceptor
    instance.interceptors.response.use(result= > {
      removePendingKey(result.config)
      return Promise.resolve(result.data)
    }, error= > {
      error.config && removePendingKey(error.config)
      const { response } = error
      if (response) {
        errorHandler(response.status)
        return Promise.reject(response)
      } else {
        if (window.navigator.onLine) {
          tip('Disconnected')}else {
          return Promise.reject(error)
        }
      }
    })
  }

  // Create an instance of the request. You can also send DELETE and PUT requests
  request (options) {
    const instance = axios.create()
    const newOptions = Object.assign(this.getInstanceConfig(), options)
    // Interceptor operation
    this.interceptors(instance)
    return instance(newOptions)
  }

  / / get request
  get (url, config) {
    const options = Object.assign({
      method: 'GET'.url: url
    }, config)
    return this.request(options)
  }

  post (url, data) {
    return this.request({
      url,
      method: 'POST',
      data
    })
  }
}

export default HttpRequest
Copy the code