Encapsulating Axios in Vue projects

Time:2021-10-19

There must be some operations when we write Vue projects. We will process the data, so we need to encapsulate a function to send requests; Before the request or response, we need to deal with the following:

//Export a function that can send requests
import axios from 'axios'
/**
*Import according to your own project. If you need to jump back, import router
*If you need to store this, import the locally stored JS you have written
*
*/


//Create an Axios instance
const instance = axios.create({
//Configure
baseUrl:null
})
//Request interceptor
instance.interceptors.request.use(config=>{
       console.log(config)
       //What to do before the request, such as adding the request header config.header. Custom = 'xxx' // the return value must be return config after the request is completed
},err=>Promise.reject(err))
//Response interceptor
instance.interceptors.response.use(res=>{
//Response, res is the data of the response
//We can capture data and process it
try{
  //Look at the data structure and click on it, so that the data can be used directly
  return res.XXX
}catcf(e){
  //Exception caught
  //Bring the original data intact
  return res
}
},err=>{
  //Response failed
  //Response failed做一些处理 // 处理完也要返回一个promise return Promise.reject(err)
}

/**
*
*Because our original intention is to export a function that can send requests. The previous processing is to take the data * * and use it directly
*
*/
export default (url,method,data) =>{
  //We have encapsulated an Axios, so we use this to send requests
  instance({
   url,
   method,
   //An expression can be written in the array, and the result must be a string. The request processing method is unified in lowercase regardless of case
   [method.toLowerCase() === 'get'? 'params' : 'data']:data

    })
}

In main.js:

import http from '@/axios.js'

//Add to the prototype of Vue so that you can get this

Vue.prototype.$http = http

 

Recommended Today

IOS segmented pop-up window

Recently, I encountered a demand similar to the segmented pop-up window of Gaode map (as shown in the figure below). I didn’t find relevant information on the Internet, so I wrote one myself, hoping to provide you with ideas. Realization effect The idea is that when the pop-up window is in the first segment, add […]