request body is undefined when trying to POST in express

Viewed 82

For some reason, request body is undefined when trying to make a post request:

here is my router: router.route("/").post(schoolController.createSchool);

here is what I put in schoolController for createSchool:

exports.createSchool = async (req, res) => {
  try {
    console.log(req.body);
    // return undefined

    const newSchool = await School.create(req.body);

    res.status(201).json({
      status: "success",
      data: {
        school: newSchool,
      },
    });
  } catch (err) {
    res.status(400).json({
      status: "fail",
      message: err,
    });
  }
};

adding on, I am following jonas's nodejs course on udemy, and he has almost the exact thing as this, except its for handling tour requests instead of school

1 Answers

The problem you are facing here is likely that you have not configured the body-parser middleware correctly. The normal req will not contain any property by the name body. Only once the request passes through the body-parser middleware, the body key will be added to the req. You can try console logging req. If the request is logged correctly, it is more than likely that you need to look into configuring you bodyparser middleware correctly before you can use req.body in your code.

Related