0

I'm making a registration page that sends a players data to the backend to then be processed. I want my page to display the error that occurred whilst trying to log in.

This is what I currently have as fetch. It works great but I want to display the exact error that occurred.

    fetch(url,
        {
            method: "POST",
            body: JSON.stringify(registration),
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        })
        .then((response) => {
            if (response.status === 200) {
                location.href = "../login/login.html";
            } else {
                throw `Error with status ${response.status}.`;
            }
        })
        .catch((error) => {
            showError(error);
        });

In inspector mode, in the network tab, I found this as response payload:

{"errors":{"Email":["The Email field is not a valid e-mail address."],"Password":["The field Password must be a string or array type with a minimum length of '6'."]},"title":"One or more validation errors occurred.","status":400,"traceId":"something"}

I'd like to display that the errors but when I try

console.log(response.errors)

I get undefined.

In short. I want to be able to access the JSON in the response payload in my javascript.

PinkDraconian
  • 501
  • 1
  • 4
  • 11
  • 1
    So it looks like your server returns a json to you, so use like this: `const content = await response.json();` or you can just `return response.json()` and then `.then(json => console.log(json.errors))` – extempl Apr 11 '19 at 17:10
  • Thanks! This is what I was looking for! – PinkDraconian Apr 11 '19 at 17:35
  • your question has answer in here [How can I get the status code from an HTTP error in Axios?](https://stackoverflow.com/questions/39153080/how-can-i-get-the-status-code-from-an-http-error-in-axios) – Fuad Rifki Oct 17 '21 at 03:36

0 Answers0