Express.js Routing Basics
Imagine you're at a large hotel. You go to the reception and ask, "Where is the swimming pool?" The receptionist directs you to the right floor and room. In web applications, **routing** works exactly like that receptionist – it directs incoming requests to the right handler based on the URL and HTTP method.
What is Routing?
Routing refers to determining how an application responds to a client request to a particular endpoint (URI) and a specific HTTP method (GET, POST, etc.). Each route can have one or more handler functions that execute when the route is matched.
Think of routes as a map for your application. When a request arrives, Express looks at its map (your routes) and sends the request to the right destination.
Route Structure
A route definition in Express has this basic structure:
app.METHOD(PATH, HANDLER);| Component | Description |
|---|---|
app | Your Express application instance. |
METHOD | HTTP method (get, post, put, delete, etc.) in lowercase. |
PATH | The URL path (e.g., '/' for home, '/about', '/users'). |
HANDLER | Function that runs when the route is matched. |
Basic Route Examples
const express = require('express');const app = express();
<!-- Home page route -->app.get('/', (req, res) => { res.send('Welcome to the Home Page!');});
<!-- About page route -->app.get('/about', (req, res) => { res.send('About Us');});
<!-- Contact page route -->app.get('/contact', (req, res) => { res.send('Contact Us');});
app.listen(3000);The Route Handler Function
The handler function receives two important objects:
req(Request): Contains information about the HTTP request (headers, parameters, body, etc.).res(Response): Used to send back the response to the client.
Response Methods
| Method | Description |
|---|---|
res.send() | Sends the HTTP response (can be string, object, array, etc.). |
res.json() | Sends a JSON response. |
res.status() | Sets the HTTP status code. |
res.redirect() | Redirects to another URL. |
res.render() | Renders a view template. |
Route Order Matters
Express executes routes in the order they are defined. If you have overlapping routes, the first one that matches wins.
<!-- This will work -->app.get('/user/:id', (req, res) => { res.send('User profile');});
<!-- This will NEVER be reached if placed AFTER the above route -->app.get('/user/profile', (req, res) => { res.send('User profile page');});Two Minute Drill
- Routing directs requests to specific handlers based on URL path and HTTP method.
- Basic syntax: `app.METHOD(PATH, HANDLER)`.
- Handler functions receive `req` (request) and `res` (response) objects.
- Use `res.send()` to respond with text/HTML, `res.json()` for JSON data.
- Route order matters – define more specific routes before general ones.
Need more clarification?
Drop us an email at career@quipoinfotech.com
