Tichel
Tichel

Reputation: 531

How to get a backend error message on the frontend using Fetch

I don't understand how fetch works for returning error messages from the backend to the frontend. I am not exactly sure what kind of properties to add to the error code in the fetch function on the frontend side. The goal is to send the error ("The email address is..") and display it in the UI.

Backend post request detail. If the user is already registered, throw a 400 error.

const signupPost = function (req, res) {
  Base.findOne({
    userName: req.body.userName
  }, 
  function (user, err) {
    if (err) {
      return res.status(400).send({
        error: 'The email address you have entered is already associated with another account.'
      });
    }

Here's the method in my Vue frontend with the error handling:

methods: {
  signup() {
    this.errorMessage = '';

    if (this.validUser()) {
      const body = {
        userName: this.user.userName,
        firstName: this.user.firstName,
        lastName: this.user.lastName,
        telephone: this.user.telephone,
        password: this.user.password
      }

      fetch(SIGNUP_URL, {
        method: 'POST',
        body: JSON.stringify(body),
        headers: {
          'content-type': 'application/json'
        }
      })
      .then((response) => {
        if (response.ok) {
          return response.json();
        }
        return response.json().then((error) => {
          throw new Error(error);
        })
      })
      .then(user => {
        console.log(user)
      })
      .catch((error) => {
        this.errorMessage = error
      });
    }
  },

Upvotes: 0

Views: 14618

Answers (1)

Radu Diță
Radu Diță

Reputation: 14171

You are almost there. You should access error inside your returned body:

return response.json().then((body) => {
  throw new Error(body.error)
})

And then use message on the error object returned:

.catch((error) => {
  this.errorMessage = error.message
})

Upvotes: 1

Related Questions