2

I am working with mongoose and axios in node.js/react and need to obtain the specific validation error in the client side so that i can update the form. In this case the user email is already the database and not unique. the error returned to the front end appears useless. i tried err.message on the front end but it gives me nothing. How do i call the specific error message telling me the actual error?

FRONTEND API IS CALLED AND INCLUDES:

  API.createUser({
    userEmail: this.state.profile.email.toLowerCase(),
   })
    .catch(err => console.log(err))

BACKEND CONTROLLER

  db.WmUser
      .create(req.body)
      .then(dbModel => res.json(dbModel))
      .catch(err => res.status(422).json(err));

MONGOOSE SCHEMA INCLUDES:

userEmail: {type: String, unique: true, required: true},

RESULT RETURNS FRONT END ERROR:

Error: Request failed with status code 422
    at createError (createError.js:16)
    at settle (settle.js:18)
    at XMLHttpRequest.handleLoad (xhr.js:77)

RESULT RETURNS IN THE BACKEND IN CONTROLLER:

if i use the following code in the controller i get the error message i need but don't know how to bring it back to the front end:

  .catch(err=> console.log(err.message))

2 Answers 2

1

The problem was the way i was calling the error in the front end. it needs to be error.response incase anyone runs into this problem

FUNCTION CALLING AXIOS IN FRONT END

  API.createUser({
    userEmail: this.state.profile.email.toLowerCase(),
        })
   .then(function (response) {
    console.log(response);
   })
   .catch(function (error) {
    if(error.response.data.code == 11000){
      console.log("THE EMAIL IS ALREADY IN THE DATABASE");
    }
    console.log(error.response);
   })

AXIOS FUNCTION IN API file

createUser: function(userData){ 
     return axios.post("/api/wmUser/", userData);
    }
Sign up to request clarification or add additional context in comments.

Comments

0

try like below in backend controller

var WmUser = require('./path/to/WmUser.js')//your db mdel path
WmUser(req.body).save().then(dbModel => res.json(dbModel))
    .catch((err) => {
        console.error('Creation fail error---->', err);
        res.status(422).json(err)
    });

1 Comment

nope says it's deprecated to use res.send(status, body): Use res.status(status).send(body).. wierd thing is i can see the error in the backend if i use .catch(err=> console.log(err.message)) just have no idea how to bring back the error message to the frontend

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.