本文介紹了在 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 XMLHTTPRequest
s.
(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 請求和響應的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!