[英]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')
当我尝试发送发布请求并检查它是否为空时,它会给出错误
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
如评论中所述,您可能需要一个主体解析中间件,例如
body-parser
Next, before we can destructure req.body
we need to check that there is a text
property接下来,在我们解构
req.body
之前,我们需要检查是否有text
属性
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.在我们知道我们确实拥有 text 属性之后,我们可以进行额外的验证。 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在调用
.trim()
方法时添加可选链接
text = text?.trim()
if (!text) {
// ... error logic
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.