您的位置:首页 > Web前端 > Vue.js

vue中axios异步调用接口的坑

2020-12-11 08:46 1096 查看

背景

最近在写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

博客园:https://www.cnblogs.com/qa-freeroad/

51cto:https://blog.51cto.com/14900374


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: