0

This is my code to handle signUp

handleSignUp(){
    console.log('Clicked')
    fetch('http://laptopIp:9999/signUp',{
        method:'POST',
        headers:{
            Accept:'application/json',
            'Content-Type':'application/json',
        },
            body:JSON.stringify(this.state),
    })
    .then((res)=>{
        console.log("here")
        console.log(res)
        this.setState({error:false})
    }).catch((e)=>{
        console.log(e)
        console.log("in error")             
    })

this is express server handling the requset

router.post('/signUp',function(reqs,resp){


MongoClient.connect(url,{ useNewUrlParser: true },function(err,database){
    if(err){
        console.log(err)
    }else{

        var dataBases = database.db("thaparApp")

        dataBases.collection('userLogin').find({'email':reqs.body.email}).toArray(function(err,result){
            if(err){
                console.log(err)
            }else if(result[0]){
                resp.status(403).send({"error":"email is taken"})
            }else{
                if(validateEmail(reqs.body.email)){
                    dataBases.collection('userLogin').insertOne(reqs.body)
                    resp.send()
                }else{
                    resp.status(403).send({"error":"Email is not correct"})
                }
            }
        })

    }
})

}) }

What i am doing is sending same username from react-native and express is sending me error 403 but React native is not handling that error in .catch() instead keeping that in .then()

enter image description here as we can see in image That status code is 403 which is error and .catch() have console.log("in error") which is not getting print.

Rajan Lagah
  • 2,373
  • 1
  • 24
  • 40
  • Possible duplicate of [How to handle HTTP code 4xx responses in fetch api](https://stackoverflow.com/questions/40248231/how-to-handle-http-code-4xx-responses-in-fetch-api) – JJJ Sep 07 '18 at 12:55

1 Answers1

2

The call is coming back from the server, although it's status is not what you expected, it's not an error to catch.

Try using fetch's ok to check whether the response was valid, for example:

.then(function(response) {
    if (!response.ok) {
        //throw error
    } else {
       //valid response
    }
})

You can also access the response's status like:

response.status;

or also, statusText such as:

response.statusText;

checkout the below:

https://developer.mozilla.org/en-US/docs/Web/API/Response/statusText

https://developer.mozilla.org/en-US/docs/Web/API/Response/status

https://www.tjvantoll.com/2015/09/13/fetch-and-errors/

JRK
  • 3,686
  • 1
  • 13
  • 19