Intercept fetch() API requests and responses in JavaScript(在 JavaScript 中拦截 fetch() API 请求和响应)
问题描述
我想在 JavaScript 中拦截 fetch API 请求和响应.
I want to intercept fetch API requests and responses in JavaScript.
例如,在发送请求之前我要截取请求的 URL.我也想在响应到达后拦截它.
For example, before sending the request I want to intercept the request URL. I'd like to intercept the response once it arrives as well.
以下代码用于拦截所有XMLHTTPRequest的响应.
The below code is for intercepting responses of all XMLHTTPRequests.
(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 实现相同的功能.我该怎么做?
I want to implement the same feature for fetch() API. How can I do this?
推荐答案
为了拦截获取请求和参数,我们可以采用下面提到的方式.它解决了我的问题.
For intercepting the fetch request and parameter we can go for below mentioned way. its resolved my issue.
const constantMock = window.fetch;
window.fetch = function() {
// Get the parameter in arguments
// Intercept the parameter here
return constantMock.apply(this, arguments)
}
这篇关于在 JavaScript 中拦截 fetch() API 请求和响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 JavaScript 中拦截 fetch() API 请求和响应
基础教程推荐
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
