1
votes

I´m trying to authenticate using axios, but when is error 400 or 401, in the cases of missing or wrong email and password I can't get the response message from the API, console logging axios error only shows me this:

error => Error: Request failed with status code 400 at createError (1.chunk.js:104463) at settle (1.chunk.js:104697) at XMLHttpRequest.handleLoad (1.chunk.js:103940)

Dont know how to get the proper response, which is this: {"errors":[{"message":"Please supply e-mail and password."}]}

Here is my code

(...)

axios.post('some api for authentication',
        {
            email: formData.email,
            password: formData.password,
            remember: formData.remember
        })
        .then(response => {
          token = response.data.session.user
          console.log('response =>', token)
        })
        .catch((error) => {
          token = null
          console.log('error =>', error)
        })

(...)

Thanks

1
Did you tried to convert the object you send JSON and test?Or Assayag
can you show us some backend code ?VersifiXion
You shared an error {"errors":[{"message":"Please supply e-mail and password."}]}. What types is errors? Which element of that type has the error? Which property on that element has the error message string? Is the issue accessing/finding an element in an array?Alexander Staroselsky
I dont know @AlexanderStaroselsky because I dont catch the error in axios, I can see this in chrome devtools as the response of the request. My problem is that I cant get this message in the error object of axios "catch"Perestrelo
Looking at axios documentation it has a section on handling errors. Try logging console.log(error.response.data); in the catch.Alexander Staroselsky

1 Answers

2
votes

Per axios handling errors the underlying error data such as message should be available at error.response.data:

.catch((error) => {
  token = null
  console.log('error =>', error.response.data)
});

You may want to use the example and handle different types of errors tht can happen:

.catch(function (error) {
  if (error.response) {
    // The request was made and the server responded with a status code
    // that falls out of the range of 2xx
    console.log(error.response.data);
    console.log(error.response.status);
    console.log(error.response.headers);
  } else if (error.request) {
    // The request was made but no response was received
    // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
    // http.ClientRequest in node.js
    console.log(error.request);
  } else {
    // Something happened in setting up the request that triggered an Error
    console.log('Error', error.message);
  }
    console.log(error.config);
});

Hopefully that helps!