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.
- Scaffolding an ExpressJS app from scratch
- AngularJS | Routing
- Routing in Node.js
- Routing Information Protocol (RIP) V1 & V2
- Laravel | Routing Basics
- Routing in Angular JS using Angular UI Router
- How to get file name from a path in PHP?
- Introduction of ALU and Data Path
- Open shortest path first (OSPF) - Set 2
- Node.js | path.parse() Method
- Node.js | path.extname() Method
- Node.js | path.normalize() Method
- Node.js | path.isAbsolute() Method
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.