FAQ: Middleware - Open-Source Middleware: Body Parsing

This community-built FAQ covers the “Open-Source Middleware: Body Parsing” exercise from the lesson “Middleware”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

Learn Express

FAQs on the exercise Open-Source Middleware: Body Parsing

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

In app.use(bodyParser.json()); why haven’t we used next(); ?

Why do we need to use app.use(bodyParser.json( ) ) for json type data. Why can’t we just use req.body ?

My guess is most of these open-source library should have included next() already, which the users won’t need to worry about.

One explanation could be… when we only want to have request in JSON format, this boydParser.json() can help filter out requests that are not in such format (e.g. text, img?)

const jellybeanBag = {
  mystery: {
    number: 4
  },
  lemon: {
    number: 5
  },
  rootBeer: {
    number: 25
  },
  cherry: {
    number: 3
  },
  licorice: {
    number: 1
  }
};

app.post('/beans/', (req, res, next) => {
  const body = req.body;  // {name: 'apple'  , number: 10}
  const beanName = body.name;
  if (jellybeanBag[beanName] || jellybeanBag[beanName] === 0) {
    return res.status(400).send('Bag with that name already exists!');
  }
  const numberOfBeans = Number(body.number) || 0;
  jellybeanBag[beanName] = {
    number: numberOfBeans
  };
  res.send(jellybeanBag[beanName]);
});

I got a question. what’s is the || jellybeanBag[beanName] === 0 means in the conditional statement? also same doubt about the const numberOfBeans = Number(body.number) || 0;.
Is it possible without the “|| jellybeanBag[beanName] === 0” and “|| 0” and the function still work with no problem ?

1 Like

I’ve been looking at this and I’d like to know this too.

The course needs a bit of updating.
Express has its own build in middleware for body parsing.
express.json() and express.urlencoded()

4 Likes

third-party middleware already have next() in their ending statements to prevent the app from hanging

I could be wrong but here’s my explanation.
In this code:

app.get('/beans/', (req, res, next) => {
  res.send(jellybeanBag);
});

We are sending back the object jellybeanBag from server to client. However, information from server is always in a string format. So we would get back something like "{mystery:{… etc. In js, we can’t really make use of that string… I mean… we can… but we would need to split/splice it so we can extract out data from it. Typically we would use json.parse(string)… but we would need to repeat that code for every instance or create a custom middleware to do that and then app.use that middleware. We then need to write another set to convert json that we send to server into string because the server only accepts strings.

the bodayParser.json() does all that hard lifting in just 2 lines, import it and use it.

1 Like

Fine that we’re being taught shortcuts, using packages such as morgan & bodyparser. But i would have preferred that we were taught the logic behind the custom coded bodyparser function earlier in the course. Instead it was skipped over with. Surely we need to understand the logic behind these processes before we’re given a shortcut that can just do it for us.

It’s because 0 is a falsey value in JavaScript

So if jellybeanBag[beanName] is either > 0 or =0 then the condition is true. In other words: A bean with that name exist.

Be aware, if you delete a bean then jellybeanBag[beanName] is set to ‘null’

app.delete('/beans/:beanName', (req, res, next) => {
  const beanName = req.beanName;
  jellybeanBag[beanName] = null;
  res.status(204).send();
});

If jellybeanBag[beanName] = null then app.use will return res.status(404).send(‘Bean with that name does not exist’);

app.use('/beans/:beanName', (req, res, next) => {
  const beanName = req.params.beanName;
  if (!jellybeanBag[beanName]) {
    return res.status(404).send('Bean with that name does not exist');
  }
  req.bean = jellybeanBag[beanName];
  req.beanName = beanName;
  next();
});

So lets say that you delete the ‘lemon’ jelly and you try to either request the ‘lemon’ jelly with a GET or delete it again with a DELETE then the console will output a 404 status error message because app.use caught the request - and app.get and app.delete are not executed.

If you make a new POST with the name ‘lemon’ then the value of jellybeanBag[‘lemon’] is changed from ‘null’ to the new value you give it (=>0).