current position:Home>Axios Foundation (VI): Axios cancel request

Axios Foundation (VI): Axios cancel request

2022-01-26 22:04:59 wb59770b05237ae



To test the effect of canceling the request , We need to json-server The service has the effect of delayed response .


Realization json-server Start mode of delayed response

       
json-server --watch db.json -d 2000
  • 1.

above 2000 It means delay 2s, Then respond to the service

Realization axios The way to cancel the request


  • Declare a global variable cancel
  • stay axios On request , To configure a cancelToken attribute , The value of this property is a CancelToken object , The parameter of the object is a callback function .
  • At the time of cancellation , Just call cancel Function .

Implementation code

       
// Declare global variables
let cancel = null;
// The first event : Send a request
btns[0].onclick = function() {
axios({
method: 'GET',
url: 'http://localhost:3000/posts',
// Add the properties of the configuration object
cancelToken: new axios.CancelToken(function(c) {
cancel = c;
})
}).then(response => {console.log(response);})
}
// The second event : Cancel the request
btns[1].onclick = function() {
cancel();
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.



copyright notice
author[wb59770b05237ae],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201262204572382.html

Random recommended