Table of contents
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ππ«‘βπΌ...