Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda