Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between using request.body or request.params in node.js?

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?

like image 601
Samir Alajmovic Avatar asked Aug 12 '13 12:08

Samir Alajmovic


People also ask

What is the difference between req body and REQ params?

req. query contains the query params of the request. req. body contains anything in the request body.

What is the use of REQ params in node JS?

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.

Can we use req body with GET request?

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.

What is the difference between params and query?

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 ...


2 Answers

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 :)

like image 74
randunel Avatar answered Oct 23 '22 23:10

randunel


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.

like image 43
WallMobile Avatar answered Oct 23 '22 21:10

WallMobile