I am wondering if there is any preference in using request.body or request.params in node.js when sending data from client to server?
req. query contains the query params of the request. req. body contains anything in the request body.
The req. params property is an object that contains the properties which are mapped to the named route "parameters". For example, if you have a route as /api/:name, then the "name" property is available as req.params.name.
Server semantics for GET, however, are restricted such that a body, if any, has no semantic meaning to the request. The requirements on parsing are separate from the requirements on method semantics. So, yes, you can send a body with GET, and no, it is never useful to do so.
Both are closely related but they are not the same at all, params are parameters set for the route, query are values resembling variable assignment that provide extra information on what is being required for the route and it will always start with a ? on the URL, inherently they are both string values that express ...
You can fit more (diverse) data in the body than in the url. You can pass any string (special characters) in the body, while encoding them in the url would get you vulnerable to status 414 (Request-URI Too Long). And it's a lot easier to use the body when passing arrays and complex objects :)
I would say that a best practice would be that you should use params when doing a get, but use body for post, put and patch.
a sample get
app.get "/api/items/:id", (req, res) ->
itemController.getItem req.params.id, (item, error) =>
if !error
res.send 'item': item
else
res.send 'error: error
a sample post
app.post "/api/items", (req, res) ->
itemController.saveItem req.body, (item, error) =>
if !error
res.send 'item': item
else
res.send 'error: error
You would add validation on as well, but this has been how I have been writing all of my endpoints.
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