Problem scenario:

In the process of a small program development, the user’s mobile phone was jammed, causing the user to click the button for many times and send multiple requests.

Solution:

CancelToken cancels ajax requests using axios cancelToken. The following is the solution code:

    /** * If requests have repetitiveRequestLimit parameter *, the operations to prevent repetition are carried out * using axios CancelToken */
  // 1. Initialize a pending file to store each request
    const pending = {};
    // 2. Judge with repetition limit parameter, with this parameter will open.
    if (config.data.hasOwnProperty("repetitiveRequestLimit")) {
      // 3. Generate a unique key to distinguish each request
      const key = `${config.url}&${config.method}&The ${JSON.stringify(
        config.data
      )}`;
      // 4. Call CancelToken
      config.cancelToken = new CancelToken((c) = > {
        // 5. Check whether the request is repeated
        if (pending[key]) {
          if (Date.now() - pending[key] > 500) {
            After 0.5 seconds, delete the corresponding request record and initiate a request again
            delete pending[key];
          } else {
            // If the request is repeated within 0.5s, cancel it
            c("repeated"); }}});// 6. Record the time when the request was initiated
      pending[key] = Date.now();
    }
Copy the code