【发布时间】:2020-10-07 14:36:26
【问题描述】:
所以在我的组件中,我有这个注册函数,它调用我的 api,在 api 中我检查电子邮件是否存在,并根据它发送适当的状态与 statusText 这是我的快速应用程序中的 api 调用处理程序:
router.post('/register',async(req,res)=>{
const {email,password,firstname,lastname}= req.body
try {
const passHash=await bcrypt.hash(password,1);
if(passHash == undefined) throw new Error('erro hassing password');
const checkEmailExistsPromise= await UserModel.findOne({email:email})
if( checkEmailExistsPromise !== null) throw new Error('EMAIL')
res.statusMessage = "user registerd ";
res.sendStatus(200);
} catch (error) {
if(error.message="EMAIL"){
res.statusMessage='email already used';
res.sendStatus(403)
}
console.log(error)
}
})
这是我在我的反应组件中的注册函数 thjat
const register=async (e)=>{
e.preventDefault()
if(!validate()) return ;
try {
const regsterUserPromise= await axios.post('http://localhost:4000/users/register',{...userInfo})
//when its a 200 status ts easy
console.log(regsterUserPromise.statusText)
} catch (error) {
//I want to get the status text of that 403 response
console.log(error)
}
}
now all I'm getting is
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/v3Rfb.png
【问题讨论】:
-
检查
error对象的字段,应该有类似“responseText”(developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/…)的内容,其中包含未解析的响应正文 -
在 reactjs 的 catch 块中。您将收到状态码为 403 的响应。因此您必须在此处自行处理
-
我知道人们对此的看法不同,但我的方法是将 http 错误保留为实际的 http 连接错误,并将状态 200 用于其他所有内容,包括应用程序逻辑错误。只需发回一个表明该邮件不存在的回复,即可轻松阅读 try 块中的消息。
-
@ChrisG 你的回答其实很有意义,也很方便
标签: javascript node.js reactjs express axios