美文网首页
axios 拦截器来截取取消重复请求

axios 拦截器来截取取消重复请求

作者: 啊笨猫 | 来源:发表于2021-03-29 11:04 被阅读0次

    在实际项目中,我们可能需要对请求进行“防抖”处理。这里主要是为了阻止用户在某些情况下短时间内重复点击某个按钮,导致前端向后端重复发送多次请求,这里介绍一种使用Axios拦截器来取消重复的请求方法

    import axios from 'axios'
    import qs from 'qs'
    import { notification, message } from 'ant-design-vue'
    import router from '@/router/router'
    import moment from 'moment'
    import baseURL from './config'
    let pending = {} // 网络请求记录
    let CancelToken = axios.CancelToken
    
    axios.defaults.timeout = 30000
    axios.defaults.baseURL = baseURL.target
        
    //设置请求拦截器
    axios.interceptors.request.use(
      config => {
        const token = localStorage.getItem('ACCESS_TOKEN')
        const companyId = localStorage.getItem('companyId')
        const userId = localStorage.getItem('userId')
        if (token) {
          config.headers['AUTH-TOKEN'] = token
        }
        if (companyId) {
          config.headers['companyId'] = companyId
        }
        if (userId) {
          config.headers['userId'] = userId
        }
        console.log(config.url, 'config.url')
        let key = `${config.url}&${config.method}&${JSON.stringify(config.data)}`
        // 设置重复请求
        config.cancelToken = new CancelToken(c => {
          if (pending[key]) {
            if (Date.now() - pending[key] > 1000) {
              // 超过1s,删除对应的请求记录,重新发起请求
              delete pending[key]
            } else {
              // 1s以内的已发起请求,取消重复请求
              c('repeated')
            }
          }
          // 记录当前的请求,已存在则更新时间戳
          pending[key] = Date.now()
        })
    
        return config
      },
      error => {
        return Promise.error(error)
      })
      // response 拦截器
    axios.interceptors.response.use(
      response => {
        let key = `${response.config.url.replace(baseURL.target, '')}&${response.config.method}&${response.config.data}`
        if (pending[key]) {
          // 请求结束,删除对应的请求记录
          delete pending[key]
        }
        if (response.data.code === 101) {
          localStorage.clear()
          router.replace('/login')
        }
        if (response.data.code === 102) {
          notification.error({
            message: response.data.msg
          })
        }
        if (response.data.code === 99) {
          message.error(response.data.msg)
          return response
        }
        return response
      },
      error => {
        if (error.response) {
          const data = error.response.data
          const token = localStorage.getItem('ACCESS_TOKEN')
          if (error.response.status === 403) {
            notification.error({
              message: '登录超时',
              description: data.msg
            })
            router.replace('/exception/403')
            return
          }
          if (error.response.status === 404) {
            notification.error({
              message: '客户端错误',
              description: data.msg
            })
            router.replace('/exception/404')
            return
          }
          if (error.response.status === 500) {
            notification.error({
              message: '服务器请求超时'
            })
            return
          }
        }
        return Promise.reject(error)
      }
    )
    
    

    相关文章

      网友评论

          本文标题:axios 拦截器来截取取消重复请求

          本文链接:https://www.haomeiwen.com/subject/pkzvhltx.html