'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 1:[1]

You can check how many keys req.body has

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

Solution 2:[2]

You can check the length of the Body :if (Objects.keys(req.body).length === 0) {

Solution 3:[3]

You can use:

if(Object.keys(req.body).length === 0)

or Object.getOwnPropertyNames(req.body).length == 0

then add your logic.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Max Pattern
Solution 3 Arman