Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if req.body is empty doesnt work with express

I tried to test my login request in postman with an empty body but this check doesn’t work. It goes beyond and execute the rest of the code. Why ?
Is there another way to check if body is empty ?

route.post("/login", (req, res) => {
  console.log(req.body);
  if (!req.body) {
    console.log("I am here");
    res.status(400).send({ message: "Content cannot be empty" });
    return;
  }
... // check password etc
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can check how many keys req.body has

if (Objects.keys(req.body).length === 0) {
    console.log("I am here");
    res.status(400).send({ message: "Content cannot be empty" });
    return;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading