0
export const registerUser = formData => async dispatch => {

    try {
        const response = await fetch('http://localhost:5000/api/users', {
            method: 'POST',
            body: formData
        })

        const data = await response.json()
        console.log(data)

        dispatch({
            type: 'auth/setToken',
            payload: data.token
        })
    } catch (err) {
        console.log(err)
    }
}

In the above code, I'm sending form data to post route. To test this out, I submitted form without any data and expected some errors from backend like name, email can't be empty. But even though request fails and gets 400 from backend, it's still not executing catch statement instead I get the errors assigned to data variable.

Yash Sharma
  • 232
  • 2
  • 12

1 Answers1

0

fetch does not reject on a HTTP error status, so you'll need to check response.ok.

const response = await fetch('http://localhost:5000/api/users', {
    method: 'POST',
    body: formData
});
if (!response.ok) {
    // handle unsuccessful request
    return;
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80