Vue project forced interruption request CancelToken

scenes to be used:

The data returned by a certain list interface is sometimes slow. At this time, if the user clicks the search button multiple times, the new data will be overwritten by the data requested last time, and the data displayed on the page is not the data the user wants to see. You can judge whether the last request has been completed every time you send a request. If it is not finished, the last request will be forcibly interrupted. The code is as follows

in request.js

import axios from 'axios'
const CancelToken = axios.CancelToken
var cancelHash = {
    
    }
const service = axios.create({
    
    
  // baseURL: process.env.NODE_ENV === 'production' ? window.productionUrl : window.developmentUrl,
  timeout: window.timeout, // request timeout
})
/**
 * 设置请求拦截器
 */
service.interceptors.request.use(
  config => {
    
    
    if (process.env.NODE_ENV === 'production') {
    
    
      config.url = window.productionUrl + config.url; // 线上打包地址
    }

    let token = localStorage.getItem('Authorization')
    if (token) {
    
    
      // 如果token不为null,否则传token给后台
      config.headers.Authorization = token
    }
    if(cancelHash[config.url]) {
    
    
      const source = CancelToken.source()
      config.cancelToken = source.token
      // source.cancel('重复请求')
      cancelHash[config.url](`取消上次${
      
      config.url}未完成请求`)
    } else {
    
    
      cancelHash[config.url] && cancelHash[config.url](`取消上次${
      
      config.url}未完成请求`)
      config.cancelToken = new CancelToken(function executor(c) {
    
    
        cancelHash[config.url] = c
      })
    }

    return config
  },
  error => {
    
    
    return Promise.reject(error)
  }
)


/*响应拦截*/
service.interceptors.response.use(
  response => {
    
    
    delete cancelHash[response.config.url]
    return response
  },
  error => {
    
    
    
  }
)

Guess you like

Origin blog.csdn.net/qq_36877078/article/details/130028612