Is there any difference between using request.body

2019-02-09 09:12发布

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?

3条回答
混吃等死
2楼-- · 2019-02-09 09:23

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

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.

查看更多
不美不萌又怎样
3楼-- · 2019-02-09 09:32

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

查看更多
Juvenile、少年°
4楼-- · 2019-02-09 09:40

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

查看更多
登录 后发表回答