简体   繁体   中英

How to proxy all XMLHttpRequest requests in a web application?

I am trying to proxy all XMLHttpRequest requests my web application is making through a proxy server. I am able to do this for all fetch requests rather easily via a service worker:

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

However, it looks like XMLHttpRequest isn't available in the service worker context (I'm not 100% certain about this but it looks like it from the spec , this Github issue and from what code I've tried). This basically leaves me with the option of monkey patching XMLHttpRequest - which definitely doesn't feel ideal.

Is there a more elegant way of doing this, other than monkey patching?

Turns out that the code provided in the question is the answer. The fetch event that is being listened to isn't just from the Fetch API; it will also intercept XHR requests too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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