FAQ: Router Parameters - Review

This community-built FAQ covers the “Review” exercise from the lesson “Router Parameters”.

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

Web Development

Learn Express

FAQs on the exercise Review

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!

This is ridiculous. Everything is the same, I went even as far as to copy-paste the code from the spice exercise and then refactor it to this exercise. Still, it is still not good enough. “Did you sent the same error resposne for a nonexistent spice?” my shiny behind…

const express = require(‘express’);
const app = express();
const bodyParser = require(‘body-parser’);

app.use(express.static(‘public’));

const PORT = process.env.PORT || 4001;

const vendingMachine = [
{
id: 1,
name: ‘Gum’,
price: 1.25,
},
{
id: 7,
name: ‘Bag of chips’,
price: 3.50,
},
{
id: 23,
name: ‘cumin’,
price: .75,
}
];

let nextSnackId = 24;

app.use(bodyParser.json());

// Add your code here:
app.param(‘snackId’, (req, res, next, id) => {
const snackIndex = vendingMachine.findIndex(snack => {
return snack.id === Number(id);
});
if (snackIndex !== -1) {
req.snackIndex = snackIndex;
next()
} else {
res.sendStatus(404);
}
});

app.get(’/snacks/’, (req, res, next) => {
res.send(vendingMachine);
});

app.post(’/snacks/’, (req, res, next) => {
const newSnack = req.body;
if (!newSnack.name || !newSnack.price) {
res.status(400).send(‘Snack not found!’);
} else {
newSnack.id = nextSnackId++;
vendingMachine.push(newSnack);
res.send(newSnack);
}
});

app.get(’/snacks/:snackId’, (req, res, next) => {
res.send(vendingMachine[req.snackIndex]);
});

app.put(’/snacks/:snackId’, (req, res, next) => {
vendingMachine[req.snackIndex] = req.body;
res.send(vendingMachine[req.snackIndex]);
});

app.delete(’/snacks/:snackId’, (req, res, next) => {
vendingMachine.splice(req.snackIndex, 1);
res.status(204).send();
});

app.listen(PORT, () => {
console.log(Server is listening on port ${PORT});
});

I mean, seriously. If you will only accept a specific configuration, a least spare me the two-faced questions. I just don’t care anymore, I will ask for the solution, but felt like I need to report this. Or I may be overreacting, it is quite possible with my current frustration level. What is wrong with my code?

6 Likes

Are we supposed to undestand the logic behind .findindex() function, other than that it returns the index, and that (-1) represents a null index?

vendingMachine.findIndex(snack => snack.id === snackId);

I similarly had frustrations with my code looking exactly like the solution code.

.findIndex() is a built-in Array method. You can learn all about it here:

Happy coding!

You can learn about .findIndex() in this CodeCademy lesson.

It returns -1 if there is no item in the array (vendingMachine) that satisfies the condition (snack.id === snackId in the example). Otherwise, it returns the index for the item satisfying the condition.

Seems like it’s a standard way of identifying an item in the database that matches with the user’s HTTP request. It’s worth remembering this technique, I guess.

I’ve been taking many lessons in CodeCademy, and my impression is that its functionality to match your code with the correct one is rather limited, especially in this Express.js tutorial series.

Still, CodeCademy gives us a good load of useful information. So I would suggest using this webpage to compare your code with the solution.

And I did it for you, which made me spot the following error:

res.sendStatus(404);

The res object has a method status(). Then it can be chained to send() method. (As we learned in this lesson.) So this part must be instead:

res.status(404).send();
1 Like

On another topic, but also related to this lesson, we have the following code:

app.get('/snacks/:snackId', (req, res, next) => {
  const snackId = Number(req.params.id);
  const snackIndex = vendingMachine.findIndex(snack => snack.id === snackId);
  if (snackIndex === -1) {
    res.status(404).send('Snack not found!');
  } else {
    res.send(vendingMachine[snackIndex]);
  }
});

In line 2, we see:

  const snackId = Number(req.params.id);

Where is req.params.id coming from considering our route specifies the name of the parameter as snackId?

In my opinion req.params.id is built in method to take a number in url query as a string. A Number() method take that as argument and give a number. Correct me, if I’m wrong.

A Number() method take that as argument and give a number. Correct me, if I’m wrong.

No, I agree that this is the case here, my issue is with the other part of the problem:

In my opinion req.params.id is built in method to take a number in url query as a string.

According to the documentation, the properties of the req.params object will be populated according to the names of the parameters provided in the route, for example:

Route path: /users/:userId/books/:bookId
Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }

In our case, we seem to have:

Route path: /snacks/:snackId
Request URL: http://localhost:3000/snacks/420
req.params: { "id": "420" }

The question is: how did we end up with a req.params.id property rather than a req.params.snackId?

1 Like

I would like to know the answer to this as well. But I thought it might be worth noting that this code also works:

app.param('snackId', (req, res, next, id) => {
  //convert snackId to a number 
  const snackId = Number(id);

I could be wrong, but I thought that perhaps the parameter id which is passed into Number is the id from from a snack object, eg

{
    id: 1,
    name: 'Gum',
    price: 1.25,
  }

In this and the previous exercise my solution was exactly the same as the provided solution and it still failed, lol.

res.sendStatus() has been used before in this tutorial (without actually being explained, lol) so it should be accepted.

Codecademy error checker often sends you on a goose chase. You spend hours trying to figure out the error, doubting yourself and your grasp of the concept, just to find out that some syntax, spacing, or variable name isn’t as expected by the error checker. I allow myself three checks before I look at the solution.
if I can’t spot an obvious difference. I use VSC git version control for comparing my code with provided solution. I have a testing file that I can paste versions of code into and git tells me what changed, Speeds up the process.

1 Like

You need to loosen the range for acceptance in this exercise.
By using a text comparison tool. I found that the only difference in my code (which was NOT accepted) and the solution code, was an exclamation sign “!” in the 404 respond message:

My code:

res.status(404).send('Snack not found');

Solution code:

res.status(400).send('Snack not found!');

That is a bit ridiculous.

1 Like

Honestly, I feel like they didn’t do as good of a job explaining express.js and middleware and they kinda introduced a couple of things and didn’t explain it and honestly after completing the “JavaScript Back-End Development” module i still feel clueless about how to even create a server and just handle query and params and just everything

1 Like

This is exactly that happened to me!! I spent 1.5 hours of my precious life, only to find out I did not put the exclamation mark in the ‘not found’ response.
This is completely ridiculous.

1 Like

This is driving me insane as far as I am aware I have the exact same logic as them yet I am getting corrected saying I called next when it returns an invalid snackId

what I have

app.param("snackId" , (req,res,next,id) => {
  let snackId = Number(id)
  let snackIndex = vendingMachine.find((snack) => {
     snack.id === snackId
  })
  if(snackIndex !== -1){
    snackId === req.snackIndex
    next();
  } else {
    res.status(404).send('Snack not found!');
  }
})

what they have

app.param('snackId', (req, res, next, id) => {
  const snackId = Number(id);
  const snackIndex = vendingMachine.findIndex(snack => snack.id === snackId);
  if (snackIndex === -1) {
    res.status(404).send('Snack not found!');
  } else {
    req.snackIndex = snackIndex;
    next();
  }
});

Did anyone even understand these lessons?!
I’m just writing code that I have no idea what it does!

What are Router Parameters actually helping me with?!

And throughout these whole lessons we were given something like this:

req.snackIndex = snackIndex;

What is this at all?!

This whole Express course is a mess. We are just told to do some stuff without actually being told what those stuff do!
At this point, if Codecademy cannot manage the Back-End course, then it really shouldn’t have any.

1 Like

For anyone struggling with this, you need to respond with res.status(404).send(‘Snack not found!’);

Make sure to include the exclamation point in the response - I was stuck on this for a lot longer than I should have been.