Which is the correct way of checking the presence of a parameter in the body?
I'm using if(req.body.hasOwnProperty('myParam')){...}
but i see that someone just write if(req.body.myParam){...}
but this second option will return false if the param has a numeric value of 0, doesn't it?
Express has a built-in express. json() function that returns an Express middleware function that parses JSON HTTP request bodies into JavaScript objects. The json() middleware adds a body property to the Express request req . To access the parsed request body, use req.
We can access these route parameters on our req. params object using the syntax shown below. app. get(/:id, (req, res) => { const id = req.params.id; });
The req. body object allows you to access data in a string or JSON object from the client side. You generally use the req. body object to receive data through POST and PUT requests in the Express server.
To use the Text body parser, we have to write app. use(bodyParser. text()) and the Content-Type in your fetch API would be text/html . That's it, now your backend service will accept POST request with text in the request body.
Right.
if you want to check if the attribute exists so hasOwnProperty
will do the job.
Using req.body.myParam
will return false for any falsely such as 0
, ''
, false
, null
or undefined
.
Also note that the dot notation and the hasOwnProperty
method do no have the same behavior :
The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
So it can be confusing, for example, run the above snippet :
var o = new Object();
if (o.toString) {
console.log('Dot notation can be confusing, inherited property example : ', o.__proto__.toString);
}
if (o.hasOwnProperty('toString')) {
// nope
} else {
console.log("that's why the hasOwnProperty method can be preferred");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With