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?
It's been over 4 years since this question was asked, however, I would still chime in to make sure somebody else stumbling upon this post has more information to understand this concept better.
req.body and req.params server two different purposes.
you would use req.body when you need to send data to a server (to store it or something), like in a "POST" request to a server. For instance, check out the following:
You are doing a "POST" request to mongodb to save a blog post. In this scenario, you would want to get the data coming in the body of the request and send it to the db. Here you would use req.body
app.post("/blog", function(req, res){
var data = req.body.blog;
.... // code to send data to the db
....
});
req.params is used when you want to extract a "param" from the url. let's say you want to extract an "id" which is part of the url. For instance "id" is the number in the following url after questions stackoverflow.com/questions/18187424/
app.get("/xyz/questions/:id", function(req, res){
var useId = req.params.id;
...
...
});
Hope, it helps.
Thanks, Kartik
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.
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 :)