reactjs - 如果状态码为400,如何获取获取响应数据

标签 reactjs error-handling fetch

我正在从api端点获取数据。
它需要用户名,电子邮件,密码,名字,姓氏并将其注册到数据库。
现在,如果发生某些错误(例如已使用的电子邮件),则会给出400状态代码并将其发送

{
    "err": "A user with the given email is already registered"
}
所以我想使用这个api端点。
在React js中,我正在这样做。
const printError=(err)=>{
    if((typeof(err)=='string'))
        return err
    else if(err.err!=undefined)
        return err.err
    else if(err.message!=undefined)
        return err.message
    else
        return 'Some error occured.Try Again later.'
}
fetch(BaseUrl+'users/signup',{
        method:'post',
        credentials:'include',
        body:JSON.stringify(user),
        headers:{
            'content-type':'application/json'
        }
    })
    .then(response=>{
        console.log(response)
        if(response.ok)
            return response.json()
        else{
            throw new Error(response)
        }
    })
    .then(response=>{
        alert(response.status)
    })
    .catch(error =>  { console.log('Registration error');console.log(error); alert('Registration Failed\nError: '+printError(error)); });

请告诉我在已经收到电子邮件后如何获取此err对象。

最佳答案

fetch提供了一个简单的ok标志,该标志指示HTTP响应的状态代码是否在成功范围内。请引用以下链接以获取更多详细信息:
https://www.tjvantoll.com/2015/09/13/fetch-and-errors/
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful

.then(response=>{
        console.log(response)// this is response from server, including all ok and error responses 
        if(response.ok)
            return response.json()
        else{
            console.log(response) ///error message for server should be in this response object only
        }
    })

关于reactjs - 如果状态码为400,如何获取获取响应数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64175523/

相关文章:

javascript - 从多个复杂子组件获取值的最佳方式?

angular - 如何处理HTTP请求中的多个错误代码方案

go - 单值上下文中的多个值

backbone.js - BackboneJS .fetch() 将响应中的一个对象放入集合中

javascript - 将菜单选项与 Material-ui 右对齐

javascript - Tailwindcss 不适用于 next.js;配置有什么问题?

python-3.x - Python Flask 错误日志无法与 HTTP 处理程序一起使用

php - PDO语句 : Getting different results between `fetchAll($mode);` and `setFetchMode($mode); fetchAll();`

JavaScript, promise {<pending>}

javascript - 无法更改 Material-UI OutlinedInput 的边框颜色