Express.js is a Node.js web flexible framework that provides a set of features for mobile and web applications. Express has various methods provide by many developers and one of the methods in the express is Router which is used to divert the user to different pages of the website base on request.
Parameter: This function accepts the following parameters:
- caseSensitive: It enables the case sensitivity means if the route is ‘/contact’ it does not mean that it is the same as ‘/Contact’, ‘/contact’ etc by default it Ignores the case sensitivity.
- mergeParams: This feature is available on express version 4.5.0 and above. You need to pass mergeParams as true if you want to access params from the Parent route via the child route.
- strict: it enables strict Routing it means if the route is ‘/about’ it does not mean that it is the same as ‘/about/’ by default it is the opposite.
Project Setup and Module Installation:
Step 1: You can visit the link to Install express module. You can install this package by using this command.
npm install express
Step 2: After installing the express module, you can check your express version in the command prompt using the command.
npm version express
Step 3: After that, you can just create a folder and add a file, for example, index.js. To run this file you need to run the following command.
Project Structure: It will look like the following.
Router() Method in Express: When your web or mobile application has many routes, a developer can’t maintain the code readability, cleanliness, consistency, and correctness by maintaining all the routes in one file. So express developer comes with a greater idea and introduce a method called Router which help developer to maintain all the requirements.
In this example project, when the user clicks on the Hello Geeks, it is redirected to http://locahost:4000/result. When the request contains the ‘/result’ route then the server runs the app.js file which is inside the routes folder.
After complete execution of the app.js file, it sends an HTML file to that particular route and shows it on the browser.
Step to run the Application: Run the index.js file by using the following command:
Output: Now open the browser and go to http://localhost:4000/, you will get the following output.