背景
最近在寫vue項目的時候遇到一個axios調用接口的坑,有個前端模塊涉及axios去調用多個接口,然后請求完獲取數據之后,再使用windows.location.href重定向到新頁面,這時候卻發現axios請求的接口都是出於canceled的狀態。
例如:
axios.get('/url1')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
axios.get('/url2')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
如果是這么寫的話,由於axios調用接口是異步的,極有可能在url1和url2還沒請求完畢的時候,windows.location.href就被執行了。這時在當前頁面打開一個新的頁面,而通過chrome的f12控制台查看url1和url2請求都是處於canceled狀態。
StackOverflow網上查的canceled解釋如下:
1.The DOM element that caused the request to be made got deleted (i.e. an IMG is being loaded, but before the load happened, you deleted the IMG node)
2.You did something that made loading the data unnecessary. (i.e. you started loading a iframe, then changed the src or overwrite the contents)
3.There are lots of requests going to the same server, and a network problem on earlier requests showed that subsequent requests weren’t going to work (DNS lookup error, earlier (same) request resulted e.g. HTTP 400 error code, etc)
簡單來說,就是元素或者請求還未完成的時候,被打斷了。
解決方法
這里有兩個方法:第一個就是直接把windows.location.href包裹在axios請求完成的處理流程里。如下面:
axios.get('/url1')
.then(function (response) {
axios.get('/url2')
.then(function (response) {
windows.location.href="/"
})
.catch(function (error) {
console.log(error);
});
})
.catch(function (error) {
console.log(error);
});
這么做的好處就是只有等到url1和url2都請求成功后,頁面才會跳轉。但是有個新的問題,如果要多次請求url1和url2之后再進行跳轉該怎么寫?例如:
for(循環) { axios.get('/url1') .then(function (response) { axios.get('/url2') .then(function (response) { }) .catch(function (error) { console.log(error); }); }) .catch(function (error) { console.log(error); }); } windows.location.href="/"
如果是這樣的話,axios請求可能還沒完成就跳轉了。axios是異步的,所以windows.location.href有可能先於axios執行完。
在這里有個取巧的方法,使用定時器來延時windows.location.href的執行時機。
setTimeout(function() { windows.location.href="/" }, 2000);
這樣寫,基本可以保證windows.location.href在axios之后執行(取決於axios調用接口的和業務邏輯處理的時間)
博主:測試生財(一個不為996而996的測開碼農)
座右銘:專注測試開發與自動化運維,努力讀書思考寫作,為內卷的人生奠定財務自由。
內容范疇:技術提升,職場雜談,事業發展,閱讀寫作,投資理財,健康人生。
csdn:https://blog.csdn.net/ccgshigao
博客園:https://www.cnblogs.com/qa-freeroad/
51cto:https://blog.51cto.com/14900374
微信公眾號:測試生財(定期分享獨家內容和資源)

