0

I am creating a mern authentication project and am stuck on a problem. When the information is sent in my register page an add user function is called on the front end

async function addUser(user) {
    const config = {
      headers: {
        "Content-Type": "application/json",
      },
    };
    try {
      await axios.post("/users/register", user, config);
    } catch (err) {}
  }

Which calls this function in my back end

exports.addUser = async (req, res, next) => {
  try {
    const { name, email, password } = req.body;
    let errors = [];
    // Check required fields
    if (!name || !email || !password) {
      errors.push("All Fields Need To Be Filled");
    }
    //Check Password Length
    if (password.length < 6) {
      errors.push("Password Needs To Be At Least 6 Characters Long");
    }
    if (errors.length > 0) {
      return res.status(201).json({
        success: false,
        errors,
      });
    } else {
      return res.status(201).json({
        success: true,
        data: req.body,
      });
    }
  } catch (error) {
    return res.status(500).json({
      success: false,
      error,
    });
  }
};

And my route

router.route("/register").post(addUser)

My question is how to get the json from the node.js function in react.js. For example if there is an error how do I get this

      return res.status(201).json({
        success: false,
        errors,

in my front end. Since this is not a get request I can't access the errors with

      const res = await axios.get("/");

If anybody knows what to do it would mean a lot if you helped

1 Answer 1

1

First off, I would recommend changing the code as a response of 201 is considered a successful "Created" response (mozilla docs).

Then, if you are using axios, you need to create an interceptor in your frontend side that will handle the response errors. Check the documentation here.

Basically you can leave the response part empty, and then throw an exception in the error function so you can handle it from the place you are making the call.

axios.interceptors.response.use(
    (response) => response,
    (error) => {
        // you can handle the error here or throw an error
        throw error;
    }
})

I recommend that you leave the interceptor and the base axios call in a separate file so it's easier for you to handle the calls and the interceptor.

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.