首页 > 解决方案 > 如何通过 javascript 拦截所有 AJAX(xhr 和 fetch) 请求?

问题描述

我有 xhr 并获取要拦截的 xhr 请求和响应类型。

获取 API 调用

我试过了

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

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

但我想编写一个通用函数来拦截所有 xhr 请求和响应。

标签: javascriptreactjs

解决方案


默认情况下, fetch() 不提供拦截请求的方法,但想出一个解决方法并不难。您可以覆盖全局 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) 
  });

`


推荐阅读