Displaying the database error in fetch

Asked

Viewed 39 times

-1

Good morning. I want to display the 400 error on front(RN) that back(Node) provides, using fetch.

function add(){
    fetch(`http://localhost:3000/AOTT7C1TT75a8s5RH1TR/${desc._id}/skaoskao`,{
        method: 'post',
        headers: {
            user:`${Home.user._id}`,
            "Authorization":`Bearer ${token}`
        }
    })
    .then(res => res.json())
    .then(res => {
        --> console.log(res)
    })
}

I can get the bug on that console.log(res) that returns to me {"error": "Você já pediu esse produto"} but I do not understand how I pass this error to mobile screen(RN)

Thank you for your attention.

1 answer

1


To display error 400, you need to use the method catch, which has the resolution of the Promise in case there is an error in making the request. An example using your code is the following:

function add(){
    fetch(`http://localhost:3000/AOTT7C1TT75a8s5RH1TR/${desc._id}/skaoskao`,{
        method: 'post',
        headers: {
            user:`${Home.user._id}`,
            "Authorization":`Bearer ${token}`
        }
    })
    .then(res => res.json())
    .catch(function(error) {
       console.log('There has been a problem with your fetch operation: ' + error.message);
   });
}

Your 400 error information is in the variable error.

For more information on using the fetch api check the MDN.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.