Why do req.params, req.query and req.body exist?

I’m new on Node.js and Express and now I’m observing that when I change the method on my calling app the params are in req.param([name]), req.body.[name] or req.query and it depends by the method.
Now my questions are two:

  1. Are there some differences between these three objects? (something that could explain why a different method refill a different object)
  2. Is there some “problems” if I create a function/module that simple check which is full and, for example, modify the req.body object so I can call this object every time to retrieve the parameters?

After @jfriend00 ‘s answer I would explain better my dilemma:
I’m developing an api and I would create a module that could check data passed with the different methods, for now I writing something like:

if(req.method== 'PUT' || req.method=='POST')

and I would do something at the beginning like:


so, after, in all my checks I will control over req.body and not the others!
Do you think that it is a bad practice?

All three properties are populated from different sources:

req.query comes from query parameters in the URL such as http://foo.com/somePath?name=ted where req.query.name === "ted".

req.params comes from path segments of the URL that match a parameter in the route definition such a /song/:songid. So, with a route using that designation and a URL such as /song/48586, then req.params.songid === "48586".

req.body properties come from a form post where the form data (which is submitted in the body contents) has been parsed into properties of the body tag.

You use the appropriate property that matches the source of the data you are interested in.

Why do req.params, req.query and req.body exist?

To give you simplified access to three different types of data.


Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *