Express.js Routing
Subject: nodejs
Express.js Routing
Routing in Express.js refers to how an application’s endpoints (URLs) respond to client requests. Each route in Express is defined by an HTTP method (GET, POST, etc.) and a path, and is associated with a callback function that handles the request and sends a response.
Routing is at the core of Express applications, enabling you to build scalable and organized web servers and REST APIs.
Basic Route Syntax
- app: An instance of Express
- METHOD: HTTP method (GET, POST, PUT, DELETE, etc.)
- PATH: The route path
- HANDLER: A function that runs when the route is matched
Example: Basic Routes
Route Parameters
You can define route parameters using a colon (:). These are placeholders for dynamic values in the URL.
Example:
Multiple Parameters
Query Parameters
Accessed via req.query:
Example:
Chaining Route Handlers
You can define multiple callback functions for a route using next():
Route Grouping with express.Router()
To organize routes by module or feature:
Example:
Wildcard Routes (404 Handling)
Key Takeaways
- Express routing maps HTTP methods and paths to request handlers.
- Route parameters and query parameters allow dynamic URLs.
- Use express.Router() to modularize and organize your routes.
- Route handlers can be chained and middleware functions added as needed.
- Routing is essential for building structured, maintainable APIs and web servers.