Until the project encountered some slightly more complex interaction, such as an input field search that required the cancellation of a previous duplicate request, the axios method with the cancellation request was wrapped with previous experience. (Skip to the end to see the full code)

1. Axios cancel event


Method 1: Cancel tokens can be created using the canceltoken. source factory method

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function(thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else{// handle error}}); axios.post('/user/12345', {
  name: 'new name'}, {cancelToken: source.token}) // Cancel the request (message argument is optional) source.cancel('Operation canceled by the user.');
Copy the code

Method two: Create the Cancel token by passing an executor function to the CancelToken constructor

const CancelToken = axios.CancelToken;
let cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(functionExecutor (c) {// The executor function accepts a cancel function as argument cancel = c; })}); // cancel the request cancel();Copy the code

When using AXIos alone, either method works, but when the wrapped AXIos method is called globally in vUE, the first problem with the method is that axios’ cancel method cancels the request that was about to be made, so use the second method

2. Encapsulation cancellation method

import axios from 'axios'// Basic configurationlet baseUrl = 'http://127.0.0.1:3000'
let timeout = 60000
Object.assign(axios.defaults, {
  baseURL: baseUrl,
  timeout,
  headers: { 'Content-Type': 'application/json; charset=UTF-8'}}) // Object holds the method for generating new CancelToken each timelet source= {} // The API is placed in this array before each request, and the request API is cleared after a successful responseletRequestList = [] / / request interceptor axios. Interceptors. Request. Use (config = > {/ /doSomething // Query status prompt... // Process the request parametersreturn config
}, function (error) {
  returnPromise. Reject (error)}) / / response interceptor axios. Interceptors. Response. Use (response = > {/ /doConst request = json.stringify (response.config.url) const Request = json.stringify (response.config.url) Requestlist.splice (requestList.findIndex(el => el === request), 1)return response
}, function(err) {// Error message failed to get configif(axios.iscancel (err)) {// Determine whether to clear the request according to the service scenario // For example, clear the request requestList.length = 0 before the page jump}else {
    console.log(err)
  }
  returnPromise.reject(err)}) // Define the cancellation method /** ** @param {*} API * @param {Boolean} allCancel */functionCancelRequest (API, allCancel){// This API exists in the request list, which is to make a repeated request and cancel the previous requestif (api && requestList.includes(api) && typeof source[api] ==='function') {source[api]('Terminate request')}else if(! API &&allCancel) {// allCancel istrueForEach (el => {forEach(el => {source[el]('Batch termination request')}}}functionRequest (method, API, params = {}, options = {}) {// Cancel the last requestif (requestList.length) cancelRequest(api)
  return new Promise((resolve, reject) => {
    if (method === 'get') {
      options.params = params
    } else {
      options.data = params
    }
    const config = Object.assign(
      {
        url: api,
        method,
        // sourceCancelToken: new axios.CancelToken(function executor(c) {
          source[api] = c; })}, Requestlist.push (API) axios.request(config).then(res => {resolve(res)}).catch(err) => {console.log(err) reject(err)})})} // Expose cancelRequest const HTTP = {//bindGet: request.bind(null,'get'),
  post: request.bind(null, 'post'),
  cancel: cancelRequest
}
export default http
Copy the code