Axios cancels a sent HTTP request and response

Time:2020-9-15

Demand scenarios

When users click purchase or other operations,httpThe response was slow

Before receiving the feedback, when the user clicks to return or jump to other pages, the request and response of the current page will be interrupted

instantiation CancelToken

The home page needs to instantiate oneCancelToken

import axios from "axios";
const CancelToken = axios.CancelToken;

Initiate a request

It is then called when a request is made

Create a variable such ascancelThe cancel method used to store this request

let cancel;
axios.get('/testApi', {
     cancelToken: new CancelToken(function executor(c) {
    cancel = c;
  })
});

callCancelToken

Call this variable when you need to cancel

It is recommended to make type judgment first, and then recharge as the initial value to ensure thataxiosOne has already been instantiatedCancelToken

if (typeof cancel===`function`){
    cancel()
    cancel=null
}

seehttpstate

staychromeIn the control panel, you can see the status of the request cancellation

Axios cancels a sent HTTP request and response

Reference documents

axiosDocument address: http://www.axios-js.com/docs/

Recommended Today

Go carbon version 1.2.0 has been released to improve and optimize the multi scenario support for orm

Carbon is a lightweight, semantic and developer friendly golang time processing library, which supports chain call, lunar calendar, Gorm, xorm and other mainstream orm If you think it’s good, please give it to a star github:github.com/golang-module/carbon gitee:gitee.com/go-package/carbon Installation and use //Using GitHub Library go get -u github.com/golang-module/carbon import ( “github.com/golang-module/carbon”) //Using gitee Library go get […]