In a front-end monitoring system, or in other scenarios, if we need to monitor the status of all requests under the current page. Perhaps normally on a request, we would choose to handle it in the callback of the request. The downside of this approach is that it invades specific business code. In normal monitoring, the code for the monitoring part and the code for the business part are separated. In addition, if there are many requests that need to be listened to, the logic for listening to requests needs to be encapsulated to reduce code duplication by hacking into specific business code.

This article uses monkey Patches to implement a request-Interceptor package that listens for requests as required.

The project address of the NPM package is: github.com/fortheallli… Welcome.

  • Gets the status and result of the API request
  • Monkey Patches implement monitoring of XMLHttpRequest requests
  • Monkey Patches enables you to monitor fetch requests

The original version of this article is on my blog: github.com/fortheallli…

Welcome to star


Get API requests and results

The way to get a request includes fetch and XMLHttpRequest. For example, here is an example of an XMLHttpRequest request:

var client = new XMLHttpRequest();
client.open("POST"."http://10.12.72.16:8080/extraInfo" );
client.setRequestHeader("Content-Type"."application/json; charset=utf-8");
client.send(JSON.stringify({}));
Copy the code

We usually use the readyStatechange from the client to determine the status of the request and get the result of the request:

client.onreadystatechange = function () {
if (client .readyState==4 &&client.status==200) {        console.log(client.responseText);//    }}Copy the code

The prototype of XMLHttpRequest has many other events besides the onReadyStatechange event, such as onAbout, onError, onLoad, onloadStart, and so on. If we want to listen for a request in its entirety, we need to implement the full implementation of these events:

client.onabout = function(){}
client.onerror = function(){}
clinet.onload = function(){}
client.onloadstart = function(){}...Copy the code

In addition, when an event occurs, a series of functions need to be implemented in sequence, which will make the internal function of the event more and more complex, making the whole project become unmaintainable.

The same is true for fetch requests, so we need to properly encapsulate the logic that listens to the request.

Implement monitoring of XMLHttpRequest requests

This article does not specify how to encapsulate the logic of listening requests through Monkey Patches. This logic is already implemented in my NPM package and can be found in my open source project:

Github.com/fortheallli…

This article only describes how to use monkey Patches. If you are interested, please read the details of how to implement monkey Patches. In the Source folder of the directory, please make an issue if you have any questions.

The NPM package is named req-interceptor. Let’s first look at how to use XMLHttpRequest requests:

import { ajaxIntercept } from 'req-interceptor';

/ / to monitor
const unregister = ajaxIntercept.register({
  requestAbout: function (xhr) {
      // xhr is real instance of a request
      console.log(xhr)
  },
  requestError: function (xhr) {
      // xhr is real instance of a request
      console.log(xhr)
  },
  requestLoad: function (xhr) {
      // xhr is real instance of a request
      console.log(xhr)
  },
});

// Send the request

var client = new XMLHttpRequest();
client.open("POST"."http://10.12.72.16:8080/extraInfo" );
client.setRequestHeader("Content-Type"."application/json; charset=utf-8");
client.send(JSON.stringify({}));

Copy the code

You simply pass in the listened object before sending the request by calling the ajaxIntercept. Register function, which returns a method to cancel the listen.

This listens for any subsequent requests. In the object of the actual parameter in ajaxIntercept. Register, the property of the object is a function with the parameter XHR, and XHR is an XMLHttpRquest that is being listened on, so we can get the specific response to the request from XHR. An example of XHR is:

xhr = {
          readyState: 4
          response: "{"success": 0}"
          responseText: "{"success": 0}"
          responseType: ""
          responseURL: "http://10.12.72.16:8080/extraInfo"
          responseXML: null
          status: 201
          statusText: "Created"
          timeout: 0
     }
Copy the code

If we are unlistening on a request, the returned unregister function is called and the request is not listened on again.

unregister();
Copy the code

We can also add more than one listener before a request:

import { ajaxIntercept } from 'req-interceptor';
/ / to monitor
constunregister1 = ajaxIntercept.register({... });constunregister2 = ajaxIntercept.register({... });constunregister3 = ajaxIntercept.register({... });/ / request
client.open(url,....)


Copy the code

If we want to remove all listeners to the request at once, we can call:

ajaxIntercept.clear();
Copy the code

Monkey Patches Implement monitoring fetch requests

The same is true for fetch requests.

import { fetchIntercept } from 'req-interceptor';


import { fetchIntercept } from 'req-interceptor';

const unregister = fetchIntercept.register({
    request: function (url, config) {
        // Modify the url or config here
        return [url, config];
    },

    requestError: function (error) {
        // Called when an error occured during another 'request' interceptor call
        return Promise.reject(error);
    },

    response: function (response) {
        // Modify the reponse object
        return response;
    },

    responseError: function (error) {
        // Handle an fetch error
        return Promise.reject(error); }});// Call fetch to see your interceptors in action.
fetch('http://google.com');
Copy the code

Fetch can only listen to request, requestError, Response, and responseError, which map the parameters of the request. The request fails. The request returned successfully, but the request returned failed.

It is also possible to cancel a listener by returning a function, and to cancel all listeners by clear.