• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

axios取消请求

武飞扬头像
CoderLonely
帮助4

axios取消请求方法一

let send_btn = document.getElementById("send_btn")       //发送请求按钮
let cancel_btn = document.getElementById("cancel_btn")	 //取消请求按钮
let cancel = null;     
send_btn.onclick = function(){
		if(cancel != null){
			cancel()     //如果上一次的请求还在继续,则取消
		}
		axios({
			method:"get",
			url:"http://localhost:3000/test.php",
			cancelToken:new axios.CancelToken(function(c){
				cancel = c
			})
		}).then(response=>{
			//处理响应数据
			cancel = null
		}).catch(reason=>{
			//错误处理
		})
}

cancel_btn.onclick = function(){
	//取消请求
	cancel()
}
学新通

axios取消请求方法二

//利用source对象创建canceltoken
let send_btn = document.getElementById("send_btn") 	 	//发送请求按钮
let cancel_btn = document.getElementById("cancel_btn")  //取消请求按钮
let source = axios.CancelToken.source();
send_btn.onclick = function(){
       // 判断上一次的请求是否还在继续,如果还在继续,则取消上一次的请求
       if(source.token._listeners!=undefined )
        {
            source.cancel("取消请求")
            source = axios.CancelToken.source()
        }
        axios.get('http://localhost:3000/front-end/axios/response.php',{
            cancelToken:source.token
            }).then(response=>{
                // 处理响应
            }).catch(reason=>{
                if(axios.isCancel(reason)){
                    console.log("取消请求",reason)
                }else{ 
                    //错误处理
                }
            })
        }
//取消按钮点击,则取消请求
cancel_btn.onclick = function(){
    source.cancel("请求已被取消")
    source = axios.CancelToken.source()
}
学新通

这篇好文章是转载于:编程之路

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 编程之路
  • 本文地址: /boutique/detail/tanhhfjfkj
系列文章
更多 icon
同类精品
更多 icon
继续加载