0

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
      });
    }
  },

1 Answer 1

1

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
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.