Intercept Fetch() API responses and request in Javascript

前端 未结 5 1957
忘掉有多难
忘掉有多难 2020-12-05 14:10

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 respons

5条回答
  •  离开以前
    2020-12-05 14:18

    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);
                })
        });
     }
    

提交回复
热议问题