in

Modify POST request body in service worker


I am trying to add a parameter to the body of a POST request in a service worker but the original body is send. I use the following code

let token = '';
self.addEventListener('message', function (event) {
    if (event.data && event.data.type === 'SET_TOKEN') {
        token = event.data.token;
    }
});

self.addEventListener('fetch', function (event) {
    const destURL = new URL(event.request.url);
    const headers = new Headers(event.request.headers);
    if (token) headers.append('Authorization', token);
    if (destURL.pathname === '/logout/') {
        const promiseChain = event.request.json().then((originalBody) => {
            return fetch(event.request.url, {
                method: event.request.method,
                headers,
                // this body is not send to the server but only the original body
                body: JSON.stringify(Object.assign(originalBody, { token })),
            });
        });
        event.respondWith(promiseChain);
        return;
    }
    const authReq = new Request(event.request, {
        headers,
        mode: 'cors',
    });
    event.respondWith(fetch(authReq));
});



Source: https://stackoverflow.com/questions/70605030/modify-post-request-body-in-service-worker

Anireel by Wondershare — The easiest custom character animated video editor

Jio, NPCI Bring UPI AUTOPAY for Convenient Mobile Recharges