How to get data from node.js when using a post request in react

Issue

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

Solution

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.

Answered By – Pietro Nadalini

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published