Home > Software design >  check if req.body is empty
check if req.body is empty

Time:12-20

When I try to send post request and check if it empty it gives error TypeError: Cannot read properties of undefined (reading 'trim')

const express = require("express");
const app = express();
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
var router = express.Router();

router.post('/api/someapi', (req, res) => {
    let{ text } = req.body;
    text = text.trim()
    if (text == "") {
        res.json({
            status: "error",
            message: "No Text"
        })
    }
})

CodePudding user response:

As mentioned in the comments, you may need a body-parsing middleware such as body-parser

Next, before we can destructure req.body we need to check that there is a text property

if(!req.body.text){
    console.log("req.body.text is either undefined, null or false!);
}

After we know that we do have the text property, we can then do additional validation. Try something like this for your purposes:

if(!req.body.text || req.body.text.trim() === ""){
    return res.json({
        status: "error",
        message: "No Text"
    });
}

//from here onwards, we know that text exists and has a valid value

CodePudding user response:

Add optional chaining while calling .trim() method

 text = text?.trim()
 if (!text) {
   // ... error logic
 }
  • Related