axios學習---取消請求
阿新 • • 發佈:2021-10-13
//獲取按鈕 const btns = document.querySelectorAll('button'); //2.宣告全域性變數 let cancel = null; //傳送請求 btns[0].onclick = function(){ //檢測上一次的請求是否已經完成 if(cancel !== null){ //取消上一次的請求 cancel(); } axios({ method:'GET', url: 'http://localhost:3000/posts', //1. 新增配置物件的屬性 cancelToken: new axios.CancelToken(function(c){ //3. 將 c 的值賦值給 cancel cancel = c; }) }).then(response => { console.log(response);//將 cancel 的值初始化 cancel = null; }) } //繫結第二個事件取消請求 btns[1].onclick = function(){ cancel(); }