最近在写vue项目的时候遇到一个axios调用接口的坑,有个前端模块涉及axios去调用多个接口,而后请求完获取数据以后,再使用windows.location.href重定向到新页面,这时候却发现axios请求的接口都是出于canceled的状态。前端
例如:vue
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); });
windows.location.href="/node
若是是这么写的话,因为axios调用接口是异步的,极有可能在url1和url2还没请求完毕的时候,windows.location.href就被执行了。这时在当前页面打开一个新的页面,而经过chrome的f12控制台查看url1和url2请求都是处于canceled状态。ios
StackOverflow网上查的canceled解释以下:chrome
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)axios
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)windows
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)app
简单来讲,就是元素或者请求还未完成的时候,被打断了。异步
这里有两个方法:第一个就是直接把windows.location.href包裹在axios请求完成的处理流程里。以下面:ide
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调用接口的和业务逻辑处理的时间)
博主:测试生财
座右铭:专一测试与自动化,致力提升研发效能;经过测试精进完成原始积累,经过读书理财奔向财务自由。
csdn:https://blog.csdn.net/ccgshigao