Day 27 of 100days of code.

Day 27 of 100days of code.

Β·

2 min read

Working with Express JS

Understanding Param Middleware

Param middleware is a special middleware which only runs for certain route parameters. To create a param middleware, we use a method called param(). Using the param() method, we can create a middleware which can only run when the value of the ID parameter is present in the URL. The method receives 2 parameters, first is the route parameter name and secondly the middleware function. The middleware function takes receives 4 parameters. 3 out of the 4 parameters have been discussed in the previous lessons except the fourth parameter which is value. The value parameter will store the value which the user passed as the ID parameter in the URL. Lets see a clear example πŸ‘‡πŸΌ

Lets check the server and request a movie object and see the response we get when we specify an ID πŸ‘‡πŸΌ

Lets also see the output on the console. We get this message on the consoleπŸ‘‡πŸΌ

In each of our route functions, we have a logic that actually checks if the requested movies is available. πŸ‘‡πŸΌ

We are repeating the above logic 3 of the route functions. We want restructure the code base and make the code cleaner. To achieve this we use use a param middleware called checkId. The value parameter will return a string so we need to convert it to a number. i.e +valueπŸ‘‡πŸΌ

To access the param middleware object on the movieRoute file πŸ‘‡πŸΌ

Lets check the server and see if our error response is still working when we try to access a valid and invalid ID. πŸ‘‡πŸΌ

and request to a valid ID still works perfectlyπŸ‘‡πŸΌ

That's all for this lesson.

Next: Chaining multiple Middleware

See you soon😊🫑✌🏼...

Β