vue中axios异步调用接口的坑
背景
最近在写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); });
windows.location.href="/
如果是这么写的话,由于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调用接口的和业务逻辑处理的时间)
博主:测试生财
座右铭:专注测试与自动化,致力提高研发效能;通过测试精进完成原始积累,通过读书理财奔向财务自由。
csdn:https://blog.csdn.net/ccgshigao
- vue学习第24天,启动本地MongoDB 启动node搭建的服务器 设置跨域 调用接口
- 解决Vue调用springboot接口403跨域问题
- Vue项目实战(五)配置 Axios api 接口调用文件
- 使用Vue实现调用接口加载页面初始数据
- vue.js中实现微信公众号中支付宝支付接口调用方法总结
- VUE+el-upload调用一次接口同时上传多个文件及表单
- Vue 调用接口流程
- 详解vue 配合vue-resource调用接口获取数据
- 「链环科技」如何利用vue-amap调用高德地图接口
- Vue之状态管理(vuex)与接口调用
- 解决vue中使用Axios调用接口时出现的ie数据处理问题
- Vue之状态管理(vuex)与接口调用
- vue结合axios实现的调用接口下载excel功能
- vue cli引入微信sdk,完成微信接口调用——引入微信sdk(一)
- vue 配合vue-resource调用接口,获取数据
- 前端js调用es接口请求传参(日志相关)ElasticStack vue
- vue cli引入微信sdk,完成微信接口调用——配置公众平台测试帐号(二)
- 前端开发手机端调用开发者工具(控制台信息,报错,接口信息等),ios安卓通用vue-cli项目中mockjs和vConsole的使用
- vue cli引入微信sdk,完成微信接口调用——使用natapp配置本机ip映射(三)
- Vue中使用axios(POST请求)调用后端接口时,后端接口接收不到前端参数的问题