如何代理 Web 应用程序中的所有 XMLHttpRequest 请求?

问题描述

我正在尝试代理我的网络应用程序通过代理服务器发出的所有 XMLHttpRequest 请求。我可以通过 Service Worker 轻松地为所有 fetch 请求执行此操作:

// sw-proxy.js
// I've trimmed out the business logic in this function - but you can see that I can easily proxy my request onwards.
self.addEventListener('fetch',e => {
    // ... some business logic
    e.respondWith(fetch('https://my-proxy-server.com'));
});

但是,看起来 XMLHttpRequest 在服务工作线程上下文中不可用(我不是 100% 确定这一点,但它看起来像来自 specthis Github issue以及我尝试过的代码)。这基本上让我可以选择猴子修补 XMLHttpRequest - 这绝对不是感觉理想的。

除了猴子补丁之外,还有更优雅的方法吗?

解决方法

原来问题中提供的代码就是答案。正在侦听的 fetch 事件不仅仅来自 Fetch API;它也会拦截 XHR 请求。