如何代理 Web 应用程序中的所有 XMLHttpRequest 请求?
How to proxy all XMLHttpRequest requests in a web application?
我正在尝试代理我的 Web 应用程序通过代理服务器发出的所有 XMLHttpRequest
请求。我可以通过服务人员轻松地为所有 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
似乎在 service worker 上下文中不可用(我不是 100% 确定这一点,但从 spec, this Github issue 和什么代码看起来是这样我试过了)。这基本上让我可以选择猴子修补 XMLHttpRequest
- 这绝对 感觉 不理想。
除了猴子修补之外,还有更优雅的方法吗?
原来问题中提供的代码就是答案。正在侦听的 fetch
事件不仅来自 Fetch API;它还会拦截 XHR 请求。
我正在尝试代理我的 Web 应用程序通过代理服务器发出的所有 XMLHttpRequest
请求。我可以通过服务人员轻松地为所有 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
似乎在 service worker 上下文中不可用(我不是 100% 确定这一点,但从 spec, this Github issue 和什么代码看起来是这样我试过了)。这基本上让我可以选择猴子修补 XMLHttpRequest
- 这绝对 感觉 不理想。
除了猴子修补之外,还有更优雅的方法吗?
原来问题中提供的代码就是答案。正在侦听的 fetch
事件不仅来自 Fetch API;它还会拦截 XHR 请求。