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

[vue] 如何中断axios的请求? #302

Open
haizhilin2013 opened this issue Jun 20, 2019 · 3 comments
Open

[vue] 如何中断axios的请求? #302

haizhilin2013 opened this issue Jun 20, 2019 · 3 comments
Labels
vue vue

Comments

@haizhilin2013
Copy link
Collaborator

[vue] 如何中断axios的请求?

@haizhilin2013 haizhilin2013 added the vue vue label Jun 20, 2019
@fengyun2
Copy link

fengyun2 commented Jul 4, 2019

cancelToken

@zhaofeipeter
Copy link

<button onclick="test()">click me</button>
<script src="https://unpkg.com/axios@0.18.0/dist/axios.js"&gt;&lt;/script>

<script>
const l = console.log;
async function test() {
const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios("http://localhost:5000/test", {
cancelToken: source.token,
})
.then(r => {
l(r.data);
})
.catch(err => {
if (axios.isCancel(err)) {
l(err.message);
} else {
console.error(err);
// handle error
}
});

source.cancel("abort。");
}
</script>

@Cai-zhiji
Copy link

可以使用 Axios 提供的 CancelToken 和 Cancel 对象来实现

CancelToken

在发送请求之前,首先创建一个 CancelToken 对象,并传递给请求配置中的 cancelToken 属性。

const { CancelToken } = axios;
const source = CancelToken.source();

axios.get('/api/user', {
  cancelToken: source.token
})
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    if (axios.isCancel(error)) {
      console.log('请求被取消', error.message);
    } else {
      console.error(error);
    }
  });

取消请求

在需要取消请求的地方,调用 source.cancel(message) 方法来取消请求,其中 message 是可选的取消消息。

// 取消请求
source.cancel('请求取消的原因');

注意:在请求被取消后,Axios 会抛出一个 Cancel 错误,并且在 error 对象上设置了 isCancel 属性为 true,可以根据该属性判断请求是否被取消。

通过使用 CancelToken 和 Cancel 对象,可以有效地中断 Axios 的请求,避免不必要的网络请求和数据处理。在需要取消请求的场景下,可以根据需要调用 cancel() 方法来取消请求。

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

No branches or pull requests

4 participants