简体   繁体   English

如何通过 javascript 拦截所有 AJAX(xhr 和 fetch)请求?

[英]How to intercept all AJAX(xhr and fetch) requests via javascript?

I have xhr and fetch type of xhr requests and responses that I want to intercept.我有 xhr 并获取要拦截的 xhr 请求和响应类型。

FETCH API CALLS获取 API 呼叫

I've tried我试过了

window.fetch =  function() {
 // Intercept the request here
}

and

XMLHttpRequest.prototype.send = function() {
// Intercept the request here
}

But I want to write one generic function which intercepts all the xhr requests and responses.但是我想写一个通用的 function 来拦截所有的 xhr 请求和响应。

By default, fetch() doesn't provide a way to intercept requests, but it's not hard to come up with a workaround.默认情况下, fetch() 不提供拦截请求的方法,但想出一个解决方法并不难。 You can overwrite the global fetch method and define your own interceptor, like this:您可以覆盖全局 fetch 方法并定义自己的拦截器,如下所示:

 fetch = (originalFetch => { return (...arguments) => { const result = originalFetch.apply(this, arguments); return result.then(console.log('Request was sent')); }; })(fetch); fetch('https://api.github.com/orgs/axios').then(response => response.json()).then(data => { console.log(data) });

` `

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM