Intercept Fetch() API responses and request in Javascript

元气小坏坏 提交于 2020-01-09 10:09:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!