In order to test the effect of canceling the request, we need to delay the response of the json-server service.
Realize the startup method of json-server delayed response
json-server --watch db.json -d 2000
The above 2000 represents a delay of 2s before responding to the service
Method to realize axios cancel request
- Declare a global variable cancel
- When axios requests, configure a cancelToken property, the value of this property is a CancelToken object, and the parameter of the object is a callback function.
- When canceling, just call the cancel function.
Implementation code
// 申明全局变量
let cancel = null;
// 第一个事件:发送请求
btns[0].onclick = function() {
axios({
method: 'GET',
url: 'http://localhost:3000/posts',
// 添加配置对象的属性
cancelToken: new axios.CancelToken(function(c) {
cancel = c;
})
}).then(response => {
console.log(response);})
}
// 第二个事件:取消请求
btns[1].onclick = function() {
cancel();
}