首页 > 解决方案 > 如何从后端访问响应状态码到前端

问题描述

后端代码:我猜这个代码是正确的,因为它在邮递员上给出了正确的错误消息。

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

前端代码:

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) 不显示状态仅显示错误消息,如何在 react.js 中访问错误状态代码或消息。并且 data.status 在上面的代码中显示未定义的反应。

标签: javascriptnode.jsmongodbexpress

解决方案


状态码是响应对象的状态属性。您需要在调用之前检查状态码(或ok 标志response.json()) 。

例子:

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

推荐阅读