Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

axios取消请求 #24

Open
YutHelloWorld opened this issue Jan 27, 2022 · 1 comment
Open

axios取消请求 #24

YutHelloWorld opened this issue Jan 27, 2022 · 1 comment
Assignees

Comments

@YutHelloWorld
Copy link
Owner

<!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" }
}
@YutHelloWorld
Copy link
Owner Author

YutHelloWorld commented Jan 27, 2022

image
image
取消请求后,计入catch错误捕获。

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

No branches or pull requests

1 participant