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

220
Visualizações
How to return the fetched API status code and response to the next step in JavaScript?

I'm using an API which returns correct HTTP code and one message related to that status code as result. I could find this solution in StackOverflow:

fetch(`${baseUrl}api/user/login`, {
    credentials: "include", // ¹ See note below
    headers: myHeaders
})
.then(function(response) {
    console.log(response.status); // Will show you the status
    if (!response.ok) {
        throw new Error("HTTP status " + response.status);
    }
    return response.json();
})
.then(// ... I need status code and error message here

but for this case, I've to use response.json() to get the error's message. So, I need a trick to return json data and status code to the next step then handle message alert.

I mean, there is not any message at first time and I've not access to the status code at next step to handle alert box's color.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The quick and dirty way is to nest then calls.

return response.json().then(parsed_json => [response.status, parsed_json])

The clearer way is to rewrite your code to use await so that all the variables remain in scope and you don't need to return them explicitly.

const response = await fetch(`${baseUrl}api/user/login`, {
    credentials: "include", // ¹ See note below
    headers: myHeaders
});
console.log(response.status); // Will show you the status
if (!response.ok) {
    throw new Error("HTTP status " + response.status);
}
const parsed_json = await response.json();
console.log(parsed_json, response.status);
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