Home > Blockchain >  how can I print error message from Nodejs backend to my frontend in MERN
how can I print error message from Nodejs backend to my frontend in MERN

Time:09-07

I am working on MERN project and I am able to send error message from the backend and I can view that message in Console => Network => Payload but I want to show that error message to my end user. I have used required in models and I have added basic error messages like Fill this field and Password does not match etc. auth.js

//REGISTER
router.post("/register", async (req, res) => {
  try {
    //generate new password
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(req.body.password, salt);
    const user1 = await User.findOne({ email: req.body.email });
    user1 && res.status(404).json("Email Already Exists");
    const user2 = await User.findOne({ username: req.body.username });
    user2 && res.status(404).json("Username already Exists");

Register.jsx

const handleClick = async (e) => {
    e.preventDefault();
    // if (email === email.current.value){
    //   email.current.setCustomValidity();
    // }
    if (passwordAgain.current.value !== password.current.value) {
      passwordAgain.current.setCustomValidity("Passwords does not match!");
     } else {
      const user = {
        username: username.current.value,
        email: email.current.value,
        password: password.current.value,
        city: city.current.value,
        from: from.current.value,
        relationship: relationship.current.value,
      };
      try {
         await axios.post("/auth/register", user);
        history.push("/login");
      } catch (err) {
        console.log(err);
      }
    }
  };

CodePudding user response:

You need to store the request response in a variable, like this:
const res = await axios.post("/auth/register", user);

Then, to log the response body, try this:
console.log(res.data);

If you want to log the error message in your catch block, try this:
console.log(err.message);

CodePudding user response:

In the front-end you will also have a response object, store that object into a variable. Var response = response from the back-end(you can use jquery, axios) Then, response.err_msg or however you named it.

  • Related