Nearby lessons
4 of 14🛣️ Routing in Express JS
📌 What is Routing?
💡 What is Routing in Express.js?
Routing in Express.js defines how an application responds to client requests at specific endpoints (URLs) using HTTP methods such as GET, POST, and others.
Each route can have one or more handler functions that run when a route is matched, allowing Express apps to handle various request types efficiently.
🧱 Step 1: Basic Setup
To begin, create a new file named index.js and set up your basic Express app structure. All your routes will be defined inside this app.
📁 Static Routes
Static routes are fixed URLs that always return the same content. These are commonly used for pages like Home, About, or Gallery.
📁 Nested and Specific Routes
Nested routes allow you to define subpaths under an existing route. You can also define specific literal paths (e.g., containing a dot).
📁 Dynamic Route Parameters
Route parameters are dynamic values in the URL that represent specific resources, such as users or products.
They are defined using a colon (:) followed by a name, and their values can be accessed using req.params.
Example URL: http://localhost:8080/user/10 → Output: { id: "10" }
🔁 Multiple Parameters (Hyphen-Separated)
You can define multiple parameters within a single route using separators such as a hyphen (-).
Express treats characters like hyphens as part of the URL path.
Example URL: http://localhost:8080/user/101-999 → Output: { uid: "101", bid: "999" }
🔍 Query Parameters
Query parameters are used to pass optional data such as filters, pagination, or search criteria.
They begin with a question mark (?) and are accessed via req.query.
Example URL: http://localhost:8080/search?name=rajesh&age=30&city=baroda