简体   繁体   中英

check if req.body is empty

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"
        })
    }
})

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

Add optional chaining while calling .trim() method

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM