【问题标题】:how to access 403's response statusText in axios [REACT , EXPRESS,NODE JS ]如何在 axios [REACT, EXPRESS,NODE JS] 中访问 403 的响应 statusText
【发布时间】: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


【解决方案1】:

所以要访问状态文本,我所要做的就是在我的 catch 块中使用 error.response.statusText

【讨论】:

  • 但是你已经有console.log(error)在里面了……你没看到文字吗?
  • 它实际上将 POST ... 403 (Not Found) 显示为字符串
猜你喜欢
  • 2018-12-24
  • 2020-08-10
  • 2020-11-12
  • 1970-01-01
  • 1970-01-01
  • 2020-11-05
  • 1970-01-01
  • 2016-06-22
  • 1970-01-01
相关资源
最近更新 更多