JavaScript-Express-CreateServer

const monsterStoreInventory = { fenrirs: 4, banshees: 1, jerseyDevils: 4, krakens: 3 };
app.get(’/monsters-inventory/:name’, (req, res, next) => {
const monsterInventory = monsterStoreInventory[req.params.name];
if (monsterInventory) {
res.send(monsterInventory);
} else {
res.status(404).send(‘Monster not found’);
}
});

Here in app.get we have a call back function with three parameters ‘req’ is for request,‘res’ is for response and ‘next’ is for what .And what is purpose of next !.

Hi,

I’ll have a go at explaining this. You’ll also find it covered in the Middleware lesson.

My understanding is that if you have created a list of routes, eg app.use, app.get, app.post etc; Express will run through them in the order in which they appear in your code until it finds the first one that matches the incoming request path. It will then use the callback attributed to that route and return the necessary response.

This works great if you only want to do one thing with that request, but sometimes we would like to do mofre. In order to do so we need to call next() at the end of the first route callback at which point Express will find the next route that matches the path and so on.

Working through the examples in the lesson will help to explain it further.

1 Like

Thanks @winningblue for the explanation.

1 Like