gpt4 book ai didi

javascript - 在 JavaScript 中拦截 fetch() API 请求和响应

转载 作者:可可西里 更新时间:2023-11-01 02:19:12 25 4
gpt4 key购买 nike

我想拦截 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);

我想为 fetch() API 实现相同的功能。我该怎么做?

最佳答案

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

accepted answer显示了用拦截调用并将参数转发给 fetch 的自定义实现替换 window.fetch 函数的一般模式。但是,显示的模式不允许拦截函数对响应做任何事情(例如,读取状态或正文或注入(inject)模拟),因此仅对记录请求参数有用。这是一个非常狭窄的用例。

This answer使用 async 函数让拦截器在 fetch promise 上 await 并大概处理响应(模拟、读取等)但是(在撰写本文时)有一个多余的闭包,并且没有说明如何非破坏性地读取响应主体。它还包含一个导致堆栈溢出的变量别名错误。

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

这是一个纠正这些问题的最小的完整示例,展示了如何处理参数日志记录,在不伤害原始调用者的情况下读取正文 by cloning the response并(可选)提供模拟响应。

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

关于javascript - 在 JavaScript 中拦截 fetch() API 请求和响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45425169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com