我想在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实现相同的功能。我该怎么做?
ok
属性 https://developer.mozilla.org/zh-CN/docs/Web/API/Response/ok:fetch(someURL).then(function(response) { if(response.ok) { /* do something */}
- sideshowbarker