Javascript 如何访问403';axios中的s响应状态文本[REACT,EXPRESS,NODE JS]
因此,在我的组件中,我有一个register函数,它调用我的api,在api中,我检查电子邮件是否存在,并根据这一情况使用statusText发送适当的状态 以下是my express应用程序中的api调用处理程序:Javascript 如何访问403';axios中的s响应状态文本[REACT,EXPRESS,NODE JS],javascript,node.js,reactjs,express,axios,Javascript,Node.js,Reactjs,Express,Axios,因此,在我的组件中,我有一个register函数,它调用我的api,在api中,我检查电子邮件是否存在,并根据这一情况使用statusText发送适当的状态 以下是my express应用程序中的api调用处理程序: router.post('/register',async(req,res)=>{ const {email,password,firstname,lastname}= req.body try { const passHash=await
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)
}
})
这是我的react组件中的寄存器函数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)
}
}
所以我访问状态文本所要做的就是
error.response.statusText
在我的catch块中检查error
对象的字段,应该有类似“responseText”(responseText)的内容,它在reactjs的catch块中包含未解析的响应体。您将收到状态代码为403的响应。因此,您必须在这里自行处理。我知道人们对此有不同的看法,但我的方法是为实际的http连接错误保留http错误,并为所有其他错误(包括应用程序逻辑错误)使用状态200。只需发送回一封表明该电子邮件不存在的回复,您就可以轻松地在try块中阅读该邮件。这是否回答了您的问题@ChrisG你的答案其实很有道理,而且很方便,但是你已经有了console.log(error)
,你没有看到文本吗?它实际上显示了POST。。。403(未找到)作为字符串
now all I'm getting is
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/v3Rfb.png