Skip to content

axios取消请求 #24

Description

@YutHelloWorld
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>axios取消请求</title>
  </head>
  <body>
    <div>
      <button class="btn">发送请求</button>
      <button class="btn">取消请求</button>
    </div>
  </body>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <script>
    // 获取按钮
    const buttons = document.querySelectorAll("button");
    // 2.声明 cancelToken
    let cancelToken = null;
    // 发送请求
    buttons[0].onclick = function () {
      axios({
        url: " http://localhost:3000/posts/1",
        method: "get",
        // 1.添加配置对象的属性
        cancelToken: new axios.CancelToken(function (c) {
          // 3.将 c 的值赋给 cancelToken
          cancelToken = c;
        }),
      })
        .then(function (response) {
          console.log(response);
        })
        .catch(function (err) {
          console.log("===>", err);
        });
    };
    // 绑定第二个按钮事件取消请求
    buttons[1].onclick = function name(params) {
      if (typeof cancelToken === "function") {
        cancelToken();
      }
    };
  </script>
</html>
json-server --watch  db.json -d 2000
{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions