问题
I want to intercept the fetch API request and response in Javascript.
For ex: Before sending the request want to intercept the request URL and once get the response wants to intercept the response.
The below code is for intercepting response of All 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);
I wan to implement the same feature for Fetch() API.
Thanks in Advance..
回答1:
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)
}
回答2:
For intercepting the response body you need to create a new Promisse and resolve or reject current into "then" code. It solved for me and keep content for real app . eg. react etc..
const constantMock = window.fetch;
window.fetch = function() {
console.log(arguments);
return new Promise((resolve, reject) => {
constantMock.apply(this, arguments)
.then((response) => {
if(response.url.indexOf("/me") > -1 && response.type != "cors"){
console.log(response);
// do something for specificconditions
}
resolve(response);
})
.catch((error) => {
reject(response);
})
});
}
回答3:
const fetch = window.fetch;
window.fetch = (...args) => (async(args) => {
var result = await fetch(...args);
console.log(result); // intercept response here
return result;
})(args);
来源:https://stackoverflow.com/questions/45425169/intercept-fetch-api-responses-and-request-in-javascript