When I got familiar with the company’s project and fumbled with the package of Axios, I found something I had never touched before.

1. Application scenarios

Basically, there was a drop down box where clicking on different options sent the same request to the server with different parameters, and the data returned was displayed in a line chart, and then I found the cancelToken thing.

Programs to cancel the previous request, brush, previous code also pretty interesting, it needs to realize the idea is, to a drop-down box two-way bind a value, and then to monitor the value, send a request to change, and then if the current request haven’t finished, the user and send a new request, will cancel the request last time, to ensure that the data is the latest users want.

2. cancelToken

First, cancelToken is given two chestnuts in the documentation on the official website. Let me give you an overview

2.1 the use ofsourcefunction

const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios.get('/user/12345', { cancelToken: source.token }).catch(function(thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else {// handle error}}); axios.post('/user/12345', { name: 'new name' }, { cancelToken: Source.token}) // Cancel the request (the message argument is optional) source.cancel('Operation Canceled by the user.');Copy the code

The axios instance will have a CancelToken attribute on top of it, which will have a source method that returns an object that the code above defines as source. In the request, the cancelToken field in the second parameter is marked source.token, so that when you execute the source.cancel method, the marked request is cancelled. So both the POST and GET requests above will be cancelled.

2.2 the use ofCancelTokenThe constructor

const CancelToken = axios.CancelToken; let cancel; axios.get('/user/12345', { cancelToken: New CancelToken(function executor(c) {// The executor function accepts a cancel function as an argument cancel = c; })}); // cancel the request cancel();Copy the code

CancelToken by passing an executor function to the axios.CancelToken constructor, the executor receives an argument that is a function that terminates the request.

2.3 And shake proof difference

According to my understanding, the purpose of implementation is the same, they all have the characteristics of preventing data confusion and conflict, canceling repeated requests, ensuring the latest data and improving performance, the difference is the different application scenarios. You know, the classic thing about anti-shaking is the submit button, say anti-shaking in the dropdown, which is hard to write, to be honest. Anti-shake can also interrupt a request with cancelToken.

3. XMLHttpRequest

Ajax isn’t really a technology or a tool, it’s a concept, a technical solution, that features the ability to partially refresh the page, and the point is that XMLHttpRequest works that way natively

xhr = new XMLHttpRequest(); xhr.open("GET","url",true); xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); Xhr.onreadystatechange = function(){if(xhr.readyState == 4 &&xhr.status == 200){alert(xhr.responseText); }} xhr.send(' parameters ');Copy the code

ReadyState Holds the state of XMLHttpRequest, 0 to 4

  • The request is not initialized
  • The server connection has been established
  • Request accepted
  • Request in process
  • Request completed and response ready.

Status is just like HTTP status codes,

It’s a bit cumbersome to use, and I haven’t used it yet. Axios is a rewrapped web request library based on Promises that can be used in both the browser and Node environments, which are based on HTTP modules and XMLHttpRequest. Axios is much easier to use

4. fetch

const url = "http://example.com/"; const options = { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json; charset=UTF-8", }, body: JSON.stringify({ a: 10, b: 20, }), }; fetch(url, options).then((response) => { console.log(response.status); });Copy the code

It’s even simpler

fetch(url).then(...) .catch(...)Copy the code

Fetch comes with the browser, it’s native, it’s not appropriate to compare it to Axios, it should be compared to XHR (chuckles), fetch is much better, supports Promise, and abstracts request and response. The advantage of FETCH is that it is supported by browser native, and the disadvantage may be that it is not superior to axios, which occupies the network request for many years, shaking its position in a short time. In addition, FETCH has appeared for a short time, so there is no mature library to encapsulate it.

5. To summarize

Axios cancelToken has two ways to interrupt a request. The axios.iscancel method determines whether a request exception was caused by a request interrupt

Ajax is a general term for asynchronous request, XMLHttpRequest and FETCH are both native request objects, and AXIOS is a wrapper based on XMLHttpRequest. Fetch and AXIOS support Promise.