What and Why ?
Routing in ExpressJS is used to subdivide and organize the web application into multiple mini-applications each having its own functionality. It provides more functionality by subdividing the web application rather than including all of the functionality on a single page. These mini-applications combine together to form a web application. Each route in Express responds to a client request to a particular route/endpoint and an HTTP request method (GET, POST, PUT, DELETE, UPDATE and so on). Each route basically refers to the different URLs in the website. So when a URL (Eg: www.geeksforgeeks.org/login) matches a route then the function associated with that specific route is executed (In this case, the function redirects the user to the login page of GeeksforGeeks).
How it is done in Express ?
Express Router is used to define mini-applications in Express so that each endpoint/route can be dealt in more detail. So, first, we will need to include express into our application. Then we have 2 methods for defining routes in the ExpressJS.
Method 1: Without using Router: Instead of using express.router, we make use of app.method (route, function)
Method 2: Using the Router: We can make use of express.router to simplify our code. Instead of specifying the path every time for a specific request, we just have to specify the path once and then we can chain the request methods to that path using the express router. The .all will be applied to all types of request methods. While the rest of them will be applied based on the request method.
Let’s save this file as test.js
Now we make use of the express router in index.js file as follows:
Note: index.js and test.js should be in the same directory.
Output: The outputs obtained via the Postman software for different request methods.