发布一个npm包,用于监控页面中的全部API请求的状态和结果

  在前端监控系统中,或者其余场景下,若是咱们须要监控当前页面下全部请求状态。可能一般请求下,咱们会选择在请求的回调中去处理。这种作法的缺点就是会侵入具体的业务代码。在一般的监控中,监控部分的代码和业务部分的代码是分离的。此外,若是存在不少的请求须要被监听,经过侵入具体业务代码,为了减小代码的重复,也须要封装监听请求的逻辑。前端

  本文经过monkey patches的方法实现了一个request-interceptor包,能够按需求监听请求。git

  该npm包的项目地址为:https://github.com/forthealll... 欢迎使用。github

  • 获取API请求的状态和结果
  • monkey patches实现监控XMLHttpRequest请求
  • monkey patches实现监控fetch请求

本文的原文在个人博客中:https://github.com/forthealll...ajax

欢迎starnpm


1、获取API请求和结果

  获取请求的方式包含了fetch和XMLHttpRequest。好比下面是一个XMLHttpRequest请求的例子:json

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({}));

  一般咱们会经过client上出发的readystatechange来判断请求的状态以及获得请求的响应结果:app

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

  XMLHttpRequest的prototype除了onreadystatechange事件外还有其余不少事件,好比onabout、onerror、onload、onloadstart等等事件。若是咱们要完整的监听一个请求,那么须要实现完整的实现这些事件:函数

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

  此外若是当某一个事件发生时,须要按顺序的实行一系列的函数,这样会使得事件函数内部愈来愈复杂,使得总体项目变的没法维护。fetch

fetch请求也是同理,所以咱们须要合理的封装监听请求的逻辑。google

2、monkey patches实现监控XMLHttpRequest请求

本文不会具体介绍如何经过monkey patches来封装监听请求的逻辑,该逻辑已经在个人npm包中实现,具体能够参考个人开源项目:

https://github.com/forthealll...

本文只介绍如何使用,若有兴趣,能够读一读具体如何实现这个monkey patches,在目录的source文件夹中,若有疑问,能够提issue。

该npm包的包名为:req-interceptor。首先来看对于XMLHttpRequest请求如何使用:

import { ajaxIntercept } from 'req-interceptor';

//监听
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)
  },
});

//发送请求

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({}));

只须要在发送请求前先调用ajaxIntercept.register函数传入监听的对象,该函数会返回一个取消监听的方法。

这样就监听以后的任意请求,在ajaxIntercept.register中的实际参数的对象中,对象的属性是一个函数,参数为xhr,xhr就是一个被监听的XMLHttpRquest,所以咱们能够从xhr中拿到请求的具体响应。xhr的一个例子为:

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
     }

若是咱们在取消对于某一个请求的监听,则调用该返回的
unregister函数,此后请求不会再被监听。

unregister();

此外咱们也能够在某一个请求前添加多个监听函数:

import { ajaxIntercept } from 'req-interceptor';
//监听
const unregister1 = ajaxIntercept.register({...});
const unregister2 = ajaxIntercept.register({...});
const unregister3 = ajaxIntercept.register({...});
//请求
client.open(url,....)

若是咱们想要一次性移除全部的对于请求的监听函数,能够直接调用:

ajaxIntercept.clear();

3、monkey patches实现监控fetch请求

对于fetch请求也是同样的。

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');

不一样的是,fetch不像XMLHttpRequest请求那样,能够监听完整的过程,fetch只有request、requestError、response和responseError这4个属性能够监听,分别映射请求的参数,请求失败,请求返回成功,请求返回失败。

一样的也能够经过返回函数来取消监听,以及经过clear函数来取消全部监听函数。

相关文章
相关标签/搜索