1. Install axios
yarn add axios
Copy the code
  1. Instantiate axios– set baseURL, timeout
const instance = axios.create({
  baseURL: ' '.timeout: 5000
})
Copy the code
  1. Request interceptor – Global injection token
instance.interceptors.request.use(config= > { // config is the request
  1. Obtain the token from the user module
  const { token } = store.state.user.profile
  if (token) config.headers.Authorization = `Bearer ${token}`
  return config// Add the token and return the request
}, e= > Promise.reject(e))
Copy the code
  1. Response interceptor – Token failure redirects to the login page and returns to the invalid page after login
instance.interceptors.response.use(res= > res.data, e= > {
  if (e.response && e.response.status === 401) {
    / / router. CurrentRoute. Value to get the current route objects
    //. FullPath gets the fullPath of the current routing object
    EncodeURIComponent encodeURIComponent encodeURIComponent encodeURIComponent encodeURIComponent encodeURIComponent encodeURIComponent
    const redirectUrl = encodeURIComponent(router.currentRoute.value.fullPath)
    router.push('/login? redirectUrl=', redirectUrl)
  }
  return Promise.reject(e)
})
Copy the code
  1. Encapsulates the request
const request = (url, method, submitData) = > {
  return instance({
    url,
    method,
    // method.tolowercase () changes the parameter passing method toLowerCase
    [method.toLowerCase() === 'get' ? 'params' : 'data']: submitData
  })
}
Copy the code
  1. Export request
export default request
Copy the code