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

256
Visualizações
How to access response status codes from backend to frontend

backend code: this code is right i guess because it gives error message correct on postman.

const userExist = await User.findOne({email:email})
        if(userExist){
             return res.status(422).send({error:"email is same"});
        }else if( password != cpassword){
            return res.status(422).send({error:"password not same"});
        }else{
            const user = new User({username,email,password,cpassword});
            await user.save();
             res.status(200).send({message:"done"});
            
        }

Frontend code:

const res = await fetch("/signup",{
  method:"POST",
  headers: {
    "Content-Type":"application/json"
  },
  body: JSON.stringify({
    username, email, password, cpassword
  })
});

const data = await res.json();
console.log(data);
if(data.status === 422){
  window.alert("Invalid Registration");
  console.log("Invalid Registration");
}
else{
  window.alert("Registration");
  console.log("Registration");

  history.push("/login");
}

Console.log(data) does not show status only shows error message, how to access error status code or messages in react.js here. And data.status shows undefined in react in above code.

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

0

The status code is the status property on the response object. You need to check the status code (or the ok flag) before calling response.json().

Example:

fetch(`${baseUrl}/signup `, {
   method:"POST",
   headers: {
    "Content-Type":"application/json"
   },
   body: JSON.stringify({
    username, email, password, password
   })
})
.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(// ...)
about 4 years ago · Juan Pablo Isaza Relatório

0

you can also do, with async await more cleaner approach as per your question, you can avoid callback hell with .then()

const res = await fetch("/signup",{
  method:"POST",
  headers: {
    "Content-Type":"application/json"
  },
  body: JSON.stringify({
    username, email, password, cpassword
  })
});

with this,

console.log(res.status)
const status = res.status;

if(status.OK){  
  window.alert("Registration");
  console.log("Registration");

  history.push("/login");
}
else{
  window.alert("Invalid Registration");
  console.log("Invalid Registration");
}
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