Table of contents
Fundamentals of nodeJS
Handling Route Parameters
Route parameters are the named URL segments that are used to capture the values specified at their position in the URL. i.e : 127.0.0.1:3000/api/v1/movies/:id
, in this case the :id
is the route parameter. when requesting the URL, in the place of :id
we specify a value. i.e : 127.0.0.1:3000/api/v1/movies/4
. In this case, the value of id=4
.
Using the GET request, this URL 127.0.0.1:3000/api/v1/movies
gets all the movies on the list but we actually want is to create an endpoint to get only a single movie with specified ID. To access the ID of a request object we use the params()
object and all the properties of the route parameters are stored as a property of that object. The ID value of the params() object is always stored as a string so before we can assign it to an actual ID we need to convert it to a number. And endpoint can also have more than route parameters. i.e: 127.0.0.1:3000/api/v1/movies/:id/:name
but in this case we also have to specify the values for each route parameters or else we run into an error. We can also make a route parameter optional by adding the ?
symbol. i.e 127.0.0.1:3000/api/v1/movies/:id/:name?
this way whether we assign a value or not, we will not get an error rather the value will return undefined
. Lets create a endpoint and test our logic๐๐ผ
Lets send a GET request, The request was successful ๐๐ผ
Lets check the console and see the output, The console returns the value of the route parameter๐๐ผ
We are using nodemon
to automatically save our changes and restart the server.
Now we want to GET our movie based on the ID specified on the route parameter and also send the movie to the response. Remember, in the params object, the ID is stored as a string so we need to first convert it to a number. To convert a string to a number, we use the plus +
operator. ๐๐ผ
Lets send the GET request and see the response ๐๐ผ
We have to write a logic to handle non existing ID or route parameters to prevent error.๐๐ผ
Lets see the server response๐๐ผ
That's all for this lesson.
Next: Handling PATCH Requests
See you soon๐๐ซกโ๐ผ...