FAQs on the exercise Route-Level app.use() - Single Path - Step 4

For the below in step 4, we’re asked to refactor beanName with req.beanName throughout the entire script. But why don’t we just replace jellybeanBag[beanName] with req.bean ? Wouldn’t that further refactor things?

app.use('/beans/:beanName', (req, res, next) => {

const beanName = req.params.beanName;

  if (!jellybeanBag[beanName]) {

    console.log('Response Sent');

    return res.status(404).send('Bean with that name does not exist');

  }

  req.bean = jellybeanBag[beanName];

  req.beanName = beanName;

  next();

});

https://www.codecademy.com/paths/back-end-engineer-career-path/tracks/becp-build-a-back-end-with-node-express-js/modules/fscp-learn-express-middleware/lessons/middleware/exercises/route-level-app-use-single-path

I think the reason is that while req.bean and jellybeanBag[beanName] have the same value, they are stored in two different places. req refers to the request object sent to the server and jellybeanBag[beanName] refers to the object already on the server. So if we need to modify anything on the server after the initial check that the bean exists, using req.bean will modify our req object, but not the object on the server.