如何中途关闭axios请求?


如何中途关闭axios请求

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./node_modules/axios/dist/axios.min.js"></script>
  <script>
  // #0. 原生的 AJAX 有取消请求的方法,xhr.abort()
  </script>
</head>

<body>
  <button id="oCancel">取消请求</button>
  <button id="oBtn">发请求</button>
  <script>
    // #1 创建全局变量,目的是为了存储取消请求的那个函数
    let cancel = null;

    oBtn.onclick = async function () {
      const r = await axios.get('https://api-hmugo-web.itheima.net/api/public/v1/home/swiperdata', {
        // #2 配置 cancelToken 参数
        cancelToken: new axios.CancelToken(function(c) {
          // c => 就是关闭当前请求的函数
          cancel = c;
        })
      })
      console.log(r.data)
    }

    oCancel.onclick = function () {
      // #3
      cancel()
    };
  </script>
</body>

</html>

文章作者: 冷杨威
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 冷杨威 !
  目录
-->