javascript - 如何从后端访问响应状态码到前端
问题描述
后端代码:我猜这个代码是正确的,因为它在邮递员上给出了正确的错误消息。
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 在上面的代码中显示未定义的反应。
解决方案
状态码是响应对象的状态属性。您需要在调用之前检查状态码(或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(// ...)
推荐阅读
- salesforce - Apex 专家挑战 1 过多的 DML 行
- javascript - 如何在 Vue 上选择一个选项
- c# - 如何评估在运行时真正使用了哪些 DLL 文件/引用?
- javascript - 为单击事件调用两次的事件处理程序
- django - 使用 Django 将数百条记录插入 SQLite 表的有效方法是什么?
- python - 为什么 Gio.Notification 没有在 Python 中显示?
- javascript - 使用 addEventListener 清除存储
- substrate - 如何实现订阅 RPC
- javascript - 如何在更改数量和折扣车表单后重新计算小计
- contentful - 内容 JSON 对象 - 无法保存到内容