【发布时间】:2018-01-07 13:46:10
【问题描述】:
我想在 JavaScript 中拦截 fetch API 请求和响应。
例如,在发送请求之前我要截取请求的 URL。我也想在响应到达后拦截它。
以下代码用于拦截所有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 实现相同的功能。我该怎么做?
【问题讨论】:
-
听起来你想侵入 Window.Request 接口 fetch.spec.whatwg.org/#request developer.mozilla.org/en-US/docs/Web/API/Request 来做类似于你在问题代码示例中所做的事情。我个人不能提供任何更具体的指导,然后说这就是你可能想要开始试验的地方
-
有什么方法可以检测到 fetch API 调用的所有成功回调吗?例如:$(document).ajaxSuccess(function(event, xhr, settings) { });
-
检查响应状态的唯一方法是检查响应对象developer.mozilla.org/en-US/docs/Web/API/Response/ok的
ok属性:fetch(someURL).then(function(response) { if(response.ok) { /* do something */} -
谢谢@sidehowbarker。我想为站点中的所有获取请求添加成功回调。我将在应用程序的顶部运行我的代码。我不知道根据回调中的请求 URL 在应用程序中注册了多少获取请求,我需要执行一些功能。
标签: javascript ajax xmlhttprequest interceptor fetch-api