devansh goyal
devansh goyal

Reputation: 71

how to get response data in fetch if status code is 400 react js

I am fetching data from a api end point. It takes username,email,password,firstname,lastname and register it to database. Now if some error occurs like email already used then it gives a 400 status code and sends this

{
    "err": "A user with the given email is already registered"
}

so I want to use this api endpoint. In react js I am doing this.

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)); });

Please tell me how to get this err object when email is already taken.

Upvotes: 1

Views: 8446

Answers (2)

devansh goyal
devansh goyal

Reputation: 71

Sorry for asking and telling the answer myself. The answer to this is throw response.json() if response.ok is false.

Upvotes: 3

Manoj
Manoj

Reputation: 2085

fetch provides a simple ok flag that indicates whether an HTTP response’s status code is in the successful range or not. Please refer below link for more details:

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
        }
    })

Upvotes: 0

Related Questions