在Javascript中拦截Fetch()API响应和请求

Har*_*ian 13 javascript ajax xmlhttprequest interceptor fetch-api

我想拦截Javascript中的fetch API请求和响应.

例如:在发送请求之前要拦截请求URL并且一旦获得响应就想拦截响应.

以下代码用于拦截所有XMLHTTPRequest的响应.

(function(open) {
 XMLHttpRequest.prototype.open = function(XMLHttpRequest) {
    var self = this;
    this.addEventListener("readystatechange", function() {
        if (this.responseText.length > 0 && this.readyState == 4 && this.responseURL.indexOf('www.google.com') >= 0) {
            Object.defineProperty(self, 'response', {
                get: function() { return bValue; },
                set: function(newValue) { bValue = newValue; },
                enumerable: true,
                configurable: true
            });
            self.response = 'updated value' //Intercepted Value 
        }
    }, false);
    open.apply(this, arguments);
};
})(XMLHttpRequest.prototype.open);
Run Code Online (Sandbox Code Playgroud)

我想为Fetch()API实现相同的功能.

提前致谢..

ggo*_*len 22

现有答案显示了fetch浏览器中模拟的一般结构,但省略了重要的细节。

接受的答案显示了更换的一般模式window.fetch与自定义实现其截取电话和转发参数的功能fetch。但是,显示的模式不会让拦截函数对响应执行任何操作(例如,读取状态或正文或注入模拟),因此仅对记录请求参数有用。这是一个非常狭窄的用例。

这个答案使用一个async函数让拦截器awaitfetch承诺上工作,并可能与响应一起工作(模拟、阅读等),但(在撰写本文时)有一个多余的闭包,并且没有显示如何读取响应正文非-破坏性地。它还包含一个导致堆栈溢出的变量别名错误。

这个答案是迄今为止最完整的,但在回调中有一些不相关的噪音,并且没有提到任何关于克隆响应以使主体能够被拦截器收集的内容。它没有说明如何返回模拟。

这是一个最小的、完整的示例,它纠正了这些问题,展示了如何处理参数日志记录,通过克隆响应和(可选)提供模拟响应,在不损害原始调用者情况下读取正文。

const {fetch: origFetch} = window;
window.fetch = async (...args) => {
  console.log("fetch called with args:", args);
  const response = await origFetch(...args);
  
  /* work with the cloned response in a separate promise
     chain -- could use the same chain with `await`. */
  response
    .clone()
    .json()
    .then(body => console.log("intercepted response:", body))
    .catch(err => console.error(err))
  ;
    
  /* the original response can be resolved unmodified: */
  //return response;
  
  /* or mock the response: */
  return {
    ok: true,
    status: 200,
    json: async () => ({
      userId: 1,
      id: 1,
      title: "Mocked!!",
      completed: false
    })
  };
};

// test it out with a typical fetch call
fetch("https://jsonplaceholder.typicode.com/todos/1")
  .then(response => response.json())
  .then(json => console.log("original caller received:", json))
  .catch(err => console.error(err))
;
Run Code Online (Sandbox Code Playgroud)

  • 这是稳定的最好答案 (5认同)

Ash*_*hUK 16

const fetch = window.fetch;
window.fetch = (...args) => (async(args) => {
    var result = await fetch(...args);
    console.log(result); // intercept response here
    return result;
})(args);
Run Code Online (Sandbox Code Playgroud)

  • 这会破坏 Chrome 83.0 中的堆栈。`const origFetch = window.fetch` 和 `await origFetch(...args)` 解决了这个问题。另外,我不确定为什么最外面的函数存在。您可以只使用 `fetch = async (...args) => ...` 并跳过 IIFE。 (6认同)

Har*_*ian 13

为了拦截获取请求和参数,我们可以采用下面提到的方式.它解决了我的问题.

 const constantMock = window.fetch;
 window.fetch = function() {
     // Get the parameter in arguments
     // Intercept the parameter here 
    return constantMock.apply(this, arguments)
 }
Run Code Online (Sandbox Code Playgroud)


Edu*_*cio 6

为了拦截响应主体,您需要创建一个新的Promisse,并将电流解析或拒绝为“ then”代码。它为我解决了,并保留了真实应用程序的内容。例如。反应等等。

const constantMock = window.fetch;
 window.fetch = function() {
  console.log(arguments);

    return new Promise((resolve, reject) => {
        constantMock.apply(this, arguments)
            .then((response) => {
                if(response.url.indexOf("/me") > -1 && response.type != "cors"){
                    console.log(response);
                    // do something for specificconditions
                }
                resolve(response);
            })
            .catch((error) => {
                reject(response);
            })
    });
 }
Run Code Online (Sandbox Code Playgroud)

  • 只是想添加一个细节:如果您需要响应主体“为特定条件做某事”,请不要忘记克隆响应,否则,promise的最终用户将得到“ TypeError:主体已被消耗”。因此,请像“ response.clone()。json()”或“ response.clone()。text()”那样获取正文。 (2认同)