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

后端 未结 3 1856
眼角桃花
眼角桃花 2021-01-02 08:13

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条回答
  • 2021-01-02 08:54

    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

    0 讨论(0)
  • 2021-01-02 08:56

    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.

    0 讨论(0)
  • 2021-01-02 08:59

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

    0 讨论(0)
提交回复
热议问题