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

251
Visualizações
How do I redirect the page if the fetch api returns status code 302

I have a button with functionality that requires the user to authenticate. If the user is not authenticated the link should redirect to the login page. When I click the button, from the devtools network tab I can see the fetch api first calls the original url which returns a status code 302 and then another call which returns the login page. So Instead of calling the login page after a 302 status code, I want to redirect the page there.

I have tried to use the location header but the result is always null and also for some reason the if(res.status == 302) block never executes

Here is the code

fetch(`https://example.com`)
    .then(res => {
        if(res.status == 302) {
            window.location.href = res.headers.get('location');
        } 
        else if (res.ok) return res.text();
        else console.log(`Error: ${res.status}`);
    })
    .then(data => {
        // Do something
    })
    .catch(e => {
        console.error(e);
    });
});
about 4 years ago · Juan Pablo Isaza
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