1

I have create backend using express and mongodb database. I am trying to fetch data in react but getting an error while fetching the data as show. Please can anyone tell what the solution of above error is and how can i fetch data from the backend

const Register = () => {
  const [values, setValues] = useState({
    name: "",
    age: "",
    country: "",
    email: "",
  });

  const setData = (e) => {
    console.log(e.target.value);
    const { name, value } = e.target;

    setValues((val) => {
      return {
        ...val,
        [name]: value,
      };
    });
  };

  const addData = async (e) => {
    e.preventDefault();

    const { name, age, country, email } = values;

    const res = await fetch("/register", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        name,
        age,
        country,
        email,
      }),
    });

    const data = await res.json();
    console.log(data);

    if (res.status === 404 || !data) {
      console.log("Error");
    } else {
      console.log("Data added successfully");
    }
  };

Here below is the backend code where the post function is performed.

router.post("/register", async (req, res) => {
  const { name, age, country, email } = req.body;

  if (!name || !age || !country || !email) {
    res.status(404).send("Some data is missing");
  }

  try {
    const preuser = await Crud.findOne({ email: email });
    console.log(preuser);

    if (preuser) {
      res.status(404).send("The user already exists");
    } else {
      let addUser = new Crud({
        name,
        age,
        country,
        email,
      });

      addUser = await addUser.save();
      res.status(201).json(addUser);
      console.log(addUser);
    }
  } catch (error) {
    res.status(404).send(error);
  }
});
    
      

1 Answers1

0

await fetch leads to an exception when the HTTP status is ≥ 400. You must add a try-catch block to handle such exceptions:

try {
  const res = await fetch("/register", {...});
} catch(exception) {
  // Handle the exception
}

Also, HTTP status 404 should be used when a resource is not found. You use it when a user already exists (where status 400 would be more appropriate) or in case of a database error (when 500 would be more appropriate).

Heiko Theißen
  • 12,807
  • 2
  • 7
  • 31