Req.body/Req.params

Hello there.

I´m working with the Personal library project in the Quality assurance section.

Freecodecamp Personal Library.

The boilerplate code I got from Github already had some preset code written on it…

For the " Test post to /api/books/{bookid}" I have the following preset code:

  app
    .route("/api/books/:id")

.post(function (req, res) {
      let bookid = req.params.id;
      let comment = req.body.comment;
    })

I don´t understand why is req.params.id and not req.body.id. If i want to add a comment, I would write the ID in the form and access it from the body. When I console.log both of them, I got the same result (I don´t understand why). I know that params are attached to the url.

Literally, if I access the route /api/books/{id} what I got is a object with my book details… It does not make sense to me to use params.

Your route includes the ID as a path parameter (as opposed to a query parameter).

When you POST, you need to post to the correct route. It is common to GET and POST to the same route. You could POST to /api/books and just include the ID in the POST payload, but that is just a less common design.

Think of it like this: the body only includes the data you want to create and you POST that data to a URL representing the object for which you want to create the data.

If the object did not exist yet in the database, then including the ID in the POST would make more sense.

It’s a design decision and you can do it however you like. Hopefully this helps you understand why it’s done the way it is in the code you’re looking at. Let me know if you understand, I can try to make it more clear.

1 Like

I still don´t understand how something I sent with req.body can be retrieved with req.params.

I think it has something to do with the html:

<form action="" method="post" id="commentTest" class="border">
    <h4>Test post to /api/books/{bookid}</h4>
    <label for="idinputtest">BookId to comment on</label>
    <input type="text" name="id" value="" id="idinputtest"><br>
    <label for="comment">Comment</label>
    <input type="text" id="comment" name="comment" value=""><br>
    <input type="submit" value="Submit">
  </form>
<script>

  /*

  *  For #sampleposting to update form action url to test inputs book id

  */

  $(function() {

    $('#commentTest').submit(function(){

      let  id = $('#idinputtest').val();

      $(this).attr('action', "/api/books/" + id);

    });

  });

</script>

At the end I understood it, it´s fine now. I wasn´t understanding the function inside jQuery.

Glad you figured it out.

For anyone with a similar problem in the future, you can see in the line quoted above that the ID is a part of the URL, and if you look at the code posted earlier, it is defined in the route as a path parameter, this is why it is available in req.params

1 Like