Home > OS >  How to access response status codes from backend to frontend
How to access response status codes from backend to frontend

Time:11-16

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.

CodePudding user response:

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(// ...)

CodePudding user response:

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");
}
  • Related