Home > Net >  Check if req.body is empty doesnt work with express
Check if req.body is empty doesnt work with express

Time:04-10

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
}

CodePudding user response:

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;
}

CodePudding user response:

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

CodePudding user response:

You can use:

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

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

then add your logic.

  • Related