Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

163
Vistas
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));
});
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Generally speaking, that should work. Here's a very similar live example that you can run and confirm:

https://glitch.com/edit/#!/materialistic-meadow-rowboat?path=sw.js%3A18%3A7

It will just POST to https://httpbin.org/#/Anything/post_anything, which will in turn echo back the request body and headers.

If your code isn't working, I would suggest using that basic sample as a starting point and slowing customizing it with your own logic. Additionally, it would be a good idea to confirm that your service worker is properly in control of the client page when its makes that request. Using Chrome DevTool's debugger interface, you should be able to put breakpoints in your service worker's fetch event handler and confirm that everything is running as expected.

Taking a step back, you should make sure that your web app isn't coded in such a way that it requires the service worker to be in control in order to go things like expire auth tokens. It's fine to have special logic in the service worker to account for auth, but make sure your code paths work similarly when the service worker doesn't intercept requests, as might be the case when a user force-reloads a web page by holding down the Shift key.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda