X-Press Publishing Project: Question on Routes

Hi all,

I’m doing the X-Press Publishing project (link), and something about the syntax for express routes isn’t clear to me.

When handling put requests, if I’m not mistaken, in the ‘theory’ portion of the course, it is mentioned that the content object is attached to the req.query property. Meaning, for example (taken from the lesson on the topic):

const monsters = { '1': { name: 'cerberus', age: '4'  } };
// PUT /monsters/1?name=chimera&age=1
app.put('/monsters/:id', (req, res, next) => {
  const monsterUpdates = req.query;
  monsters[req.params.id] = monsterUpdates;

However, in this project, the put info is always attached to req.body, not req.query:

artistsRouter.put('/:artistId', (req, res, next) => {
    if (!req.body.artist.name || !req.body.artist.dateOfBirth || !req.body.artist.biography) {

Furthermore, in the case above, not only is it attached to body and not query, but it’s included in its own artist object.

What defines how the request content is attached and how do we know when to use either?

Would appreciate if someone could clear the confusion.



I was wondering about this earlier and after reading a few posts and articles I think I have a better understanding.

So what is the difference between req.query and req.body? It all comes down to how the information is being sent.

If the data is included in the http request path(URL) as in your monsters example;
The data is not sent in the form of an object, it has been sent as a query within the URL and we can access name using req.query.name and req.query.age.

If instead we wanted our API to receive data in the body of the http request the path(URL) will be
There is no query to be extracted from this path. Instead an object is sent in the body of the request and so we access the data using req.body.monster.name and req.body.monster.age.

In either instance 1 would be a parameter which can be accessed using req.parms.id

You choose which method to use for each request when you design your API. It’s dictated to us in the projects as we are working with the structure of the existing project files.

/monsters/1 - 1 = req.param.id
/monsters/1?name=Bob - Bob = req.query.name

With monster object in request body
{monster: {name: Bob, age: 1}} - Bob = req.body.monster.name

Hope that makes sense?

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.