Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express, correct way to check the presence of a parameter in the body

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?

like image 591
lellefood Avatar asked May 31 '18 13:05

lellefood


People also ask

How do I get an Express Body request?

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.

How do you access GET parameters after Express?

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

What is req Body Express?

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.

How do you use a body parser?

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.


1 Answers

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");
}
like image 198
Guy Segev Avatar answered Oct 02 '22 19:10

Guy Segev