vue axios请求频繁时取消上一次请求 (及请求拦截 响应拦截))

方法一 取消上一次请求 cancelRequest();

 <script>
        import axios from 'axios'
        import qs from 'qs'
        
        export default {
            methods: {
                request(keyword) {
                    var CancelToken = axios.CancelToken
                    var source = CancelToken.source()
                      
                    // 取消上一次请求
                    this.cancelRequest();
                    
                    axios.post(url, qs.stringify({kw:keyword}), {
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                            'Accept': 'application/json'
                        },
                        cancelToken: new axios.CancelToken(function executor(c) {
                            that.source = c;
                        })
                    }).then((res) => {
                        // 在这里处理得到的数据
                        ...
                    }).catch((err) => {
                        if (axios.isCancel(err)) {
                            console.log('Rquest canceled', err.message); //请求如果被取消,这里是返回取消的message
                        } else {
                            //handle error
                            console.log(err);
                        }
                    })
                },
                cancelRequest(){
                    if(typeof this.source ==='function'){
                        this.source('终止请求')  这样就可以成功取消上一次请求啦!真的非常好用~
                    }
                },
            }
        }
        </script>
      

请求拦截(配置发送请求的信息)

// 请求拦截(配置发送请求的信息)
// 请求拦截    为每一次请求添加token(配置发送请求的信息)
axios.interceptors.request.use(function (config){
  // 处理请求之前的配置
  config.headers.Authorization=window.sessionStorage.getItem('token')
  return config;
  }, function (error){
  // 请求失败的处理
  return Promise.reject(error);
  });



响应拦截(配置请求回来的信息)


// 响应拦截(配置请求回来的信息)
axios.interceptors.response.use(function (response){
 // 处理响应数据
 return response;
 }, function (error){
 // 处理响应失败
 return Promise.reject(error);
 });

Vue.prototype. h t t p = a x i o s / / 其 他 页 面 在 使 用 a x i o s 的 时 候 直 接 t h i s . http = axios //其他页面在使用axios的时候直接 this. http=axios//使axiosthis.http就可以了

方法二

        

 data() {
    return {
		timer:''
    }
}                

//请求方法调用之前 取消上次的请求  也可达到目的 

   clearTimeout(that.timer)
                         
       that.timer=setTimeout(function(){
                         
        Indicator.open()
        that.httpServe.request(API.openAgreePay,'post',{
        

        }800)
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端成长营

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值