Building a web application is like designing a city. Roads lead to destinations, and buildings serve purposes. In Express, routes are the roads guiding users to the right places, and routers are the city’s districts helping us organize those roads. Let's explore how to define and manage routes and routers step by step, with real-world analogies and a follow-along exercise.
Imagine a pizza restaurant with different doors for ordering, pickup, and delivery inquiries. Each door leads to a staff member with a specific job. In Express, each route is like a door — when someone visits that URL, they’re handled by the right staff member (function).
Routes allow you to respond to different HTTP requests (GET, POST, etc.) for different URL paths, like /order, /menu, or /contact.
Folder structure:
project_folder/
├── app.js
File: app.js
const express = require('express');
const app = express();
// Define a route
app.get('/', (req, res) => {
res.send('Welcome to Pizza Planet!');
});
// Define another route
app.get('/menu', (req, res) => {
res.send('Here is our menu!');
});
// Start the server
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
Code Explanation:
app.get('/', ...) handles GET requests to the home page.res.send() sends back a response to the client’s browser.app.listen(3000, ...) starts the server on port 3000.Routes connect users to content and services. They help your app respond correctly to user interactions, like requesting a menu or submitting an order form.
Add routes for:
/order - Sends back "Place your order here."/contact - Sends back "Contact us at pizza@planet.com."As your restaurant grows, you might open new locations or departments. Managing everything from one room (file) becomes chaotic. Routers in Express are like assigning different departments to handle specific responsibilities.
Routers help split routes into multiple files. Each file handles a part of the application, like users, orders, or products.
Updated folder structure:
project_folder/
├── app.js
├── routes/
│ └── menu.js
File: routes/menu.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('Menu: Pepperoni, Veggie, Margherita');
});
router.get('/specials', (req, res) => {
res.send('Today’s Special: BBQ Chicken Pizza!');
});
module.exports = router;
Updated app.js
const express = require('express');
const app = express();
const menuRouter = require('./routes/menu');
// Use the router
app.use('/menu', menuRouter);
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
Explanation:
/menu routes are now handled by menu.js./menu shows the full menu. /menu/specials shows the specials.app.use('/menu', menuRouter) maps routes to their respective router.In a social media app:
/users router handles registration, login, and profiles./posts router manages creating, editing, and viewing posts./messages router handles private messages.Each router is isolated and manageable, making the app scalable and easy to maintain.
app.get('/menu/:item', (req, res) => {
const item = req.params.item;
res.send(`You ordered: ${item}`);
});
Visiting /menu/pepperoni responds with "You ordered: pepperoni". Route parameters let you handle dynamic content based on user input.
/api/v1/menu).req and how to format res.express.json() to handle JSON in POST requests.Routes and routers are the backbone of any Express application. Routes guide users to the right content, and routers keep everything organized behind the scenes. Think of routes as doors and routers as hallways — together, they create a smooth navigation experience for users and developers alike.
Practice by building small apps like a to-do list or blog. Add more routes, then reorganize them into routers. With these tools, you're ready to build apps that are both powerful and maintainable.