简体   繁体   English

如何使用 axios 取消正在进行的 GET 请求

[英]How do I cancel a ongoing GET request with axios

I have an inputfield, onChange it sends my value of the inputfield to an API.我有一个输入字段,onChange 它将我输入字段的值发送到 API。 So, the api will start fetching all the data.因此,api 将开始获取所有数据。 but when I continue typing again, I want that previous request to be canceled.但是当我再次继续输入时,我希望取消之前的请求。

I'm using axios for making my request and tried looking at the documentation but I can't seem to figure out how it really works, can someone explain how to do this?我正在使用 axios 提出我的请求并尝试查看文档,但我似乎无法弄清楚它是如何工作的,有人可以解释一下如何做到这一点吗?

Here is my function that gets called by every new input:这是我的 function ,每个新输入都会调用它:

const onChange = (value) => {
  setTimeout(async() => {
    let result = []

    if (y === "keyword") result = await AutoSuggestionKeyword({
      value: value
    });
    
    else {
      const CancelToken = axios.CancelToken;
      const source = CancelToken.source();

      await axios.get(`https://${api_uri}/${value.toLowerCase()}`)
        .catch(function(thrown) {
          if (axios.isCancel(thrown)) {
            console.log('Request canceled', thrown.message);
          } else {
            // handle error
          }

        }).then(resp => {
          console.log(resp)
        });
      source.cancel();
    }
  }, 500)
}

You need to provide a cancelToken in your request,您需要在请求中提供cancelToken

axios.get(`https://${api_uri}/${value.toLowerCase()}`, {
  cancelToken: source.token
}).catch(function(thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // handle error
  }

});

I don't think you can cancel an HTTP request , but what you can do is wrap it in debounce function, debounce function wait for a certain time before calling the callback or function you wrap or pass on it. I don't think you can cancel an HTTP request , but what you can do is wrap it in debounce function, debounce function wait for a certain time before calling the callback or function you wrap or pass on it.

you can simply google debounce and it will give you articles or npm packages that you can use.您可以简单地 google debounce,它会为您提供可以使用的文章或 npm 包。

I think this article also has the same issue you are trying to resolve我认为这篇文章也有您要解决的相同问题

Happy coding快乐编码

Edit 1: yeah so you can cancel the http request see comment below编辑 1:是的,所以您可以取消 http 请求,请参阅下面的评论

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM