Express.js Routing
# Express.js Routing
Welcome to Chapter 14! In the previous chapter, we created simple GET routes. But modern web applications do much more than just *get* data. Users submit forms, update their profiles, and delete comments.
To handle these actions, we use different HTTP Methods (Verbs). Additionally, we can't hardcode a route for every single user profile on a website. In this chapter, we will learn about advanced routing, RESTful verbs, and dynamic route parameters.
---
1. Introduction
Routing refers to determining how an application responds to a client request to a particular endpoint. An endpoint consists of a URI (or path) and an HTTP Request Method (GET, POST, etc.).
Express provides methods that correspond perfectly to HTTP verbs:
-
app.get(): Retrieve data.
-
app.post(): Submit/create new data.
-
app.put(): Update existing data.
-
app.delete(): Remove data.
---
2. Learning Objectives
By the end of this chapter, you will be able to:
- Create routes for different HTTP methods.
- Differentiate between GET and POST requests.
-
Understand and create dynamic routes using Route Parameters (
:id).
-
Extract dynamic data using
req.params.
-
Group routes using
express.Router()for better organization.
---
3. Beginner-Friendly Explanations
GET vs POST
- GET is like reading a book. You are asking the server for information. It is safe, and you can bookmark it. (Every time you type a URL in Chrome, it's a GET request).
-
POST is like submitting a test. You are sending data *to* the server to be saved or processed. You cannot simply type a POST URL into a browser; it usually comes from an HTML
<form>or an API request.
Dynamic Route Parameters (req.params)
Imagine Facebook. They don't write a route for app.get('/profile/mark') and app.get('/profile/sarah'). They write one Dynamic Route: app.get('/profile/:username').
The colon : tells Express that this part of the URL is a variable placeholder.
---
4. Syntax Explanation
Let's look at how to capture data from a dynamic route.
``javascript id="ch14-syntax-1"
const express = require('express');
const app = express();
// The colon ':' creates a parameter named 'userId' app.get('/users/:userId', (req, res) => { // We access the value using req.params const requestedId = req.params.userId; res.send(<h1>Viewing profile for User ID: ${requestedId}</h1>`); });
app.listen(3000);
javascript id="ch14-code-1"
// Example URL: /flights/JFK/to/LAX
app.get('/flights/:from/to/:to', (req, res) => {
const departure = req.params.from;
const arrival = req.params.to;
res.send(Searching flights from ${departure} to ${arrival}...);
});
javascript id="ch14-code-2" // When user VISITS the page (GET) app.get('/login', (req, res) => { res.send('Please fill out the login form.'); });
// When user SUBMITS the form (POST) app.post('/login', (req, res) => { // (We will learn how to extract form data in Chapter 19) res.send('Login submitted! Verifying credentials...'); });
javascript id="ch14-code-3" const express = require('express'); const router = express.Router(); // Create a mini-app
// These routes are relative to where they are mounted
router.get('/', (req, res) => res.send('Blog Home'));
router.get('/:id', (req, res) => res.send(Reading article ${req.params.id}));
module.exports = router;
javascript id="ch14-code-4" const express = require('express'); const app = express();
const blogRoutes = require('./routes/blog');
// Mount the router! All routes inside blog.js now start with /blog app.use('/blog', blogRoutes);
app.listen(3000);
javascript id="ch14-mini-project-1" // app.js const express = require('express'); const app = express();
const articleRoutes = require('./routes/articles');
app.get('/', (req, res) => res.send("Welcome to the homepage!"));
// Mount the router app.use('/articles', articleRoutes);
app.listen(3000, () => console.log('Server running...'));
javascript id="ch14-mini-project-2" // routes/articles.js const express = require('express'); const router = express.Router();
// Route: GET /articles router.get('/', (req, res) => { res.send("Here is a list of all articles."); });
// Route: POST /articles (Imagine a form submission) router.post('/', (req, res) => { res.send("New article created!"); });
// Route: GET /articles/:id
router.get('/:id', (req, res) => {
const articleId = req.params.id;
res.send(Reading article with ID: ${articleId});
});
// Route: DELETE /articles/:id
router.delete('/:id', (req, res) => {
res.send(Article ${req.params.id} has been deleted.);
});
module.exports = router;
javascript
router.get('/:username', (req, res) => res.send("Profile"));
router.get('/settings', (req, res) => res.send("Settings"));
``
Why does visiting /settings show the "Profile" page? Rearrange the code to fix it.
---
13. MCQs with Answers
Q1: How do you define a dynamic route parameter in Express?
A) By wrapping it in brackets [id]
B) By using a colon :id
C) By using a dollar sign $id
D) By using a question mark ?id
Answer: B
Q2: Which Express object holds the dynamic variables extracted from the URL?
A) req.params
B) req.query
C) req.body
D) res.data
Answer: A
Q3: Which HTTP method is typically used to create new data? A) GET B) POST C) PUT D) DELETE Answer: B
Q4: What is express.Router() used for?
A) To connect to the internet.
B) To group routes together in separate files to keep code organized.
C) To handle 404 errors automatically.
D) To serve static images.
Answer: B
---
14. Interview Questions
- 1. What is a RESTful API?
and /users/:id) to perform CRUD operations.
-
2.
Explain the difference between
req.params and req.query.
*Answer:* req.params extracts data from dynamic route paths defined with a colon (e.g., /users/:id). req.query extracts data from the URL query string after a question mark (e.g., /search?name=alice).
---
15. FAQs
Q: How do I test POST or DELETE routes if my browser only does GET requests?
A: Backend developers use specialized software like Postman, Insomnia, or the VS Code extension Thunder Client. These tools allow you to construct and send any type of HTTP request to your server to test it.
Q: Is it safe to put database IDs in the URL?
A: Yes! IDs like
/users/5 or /product/a2b4 are perfectly safe. However, you should never put sensitive data like passwords or social security numbers in the URL!
---
16. Summary
-
GET, POST, PUT, DELETE are standard HTTP methods handled easily by Express.
-
Use a colon
: to create dynamic route placeholders.
-
Access dynamic data using
req.params.
-
The order of routes matters! Static routes must go before dynamic catch-alls.
-
Use
express.Router()` to split large routing files into smaller, modular files.
---
17. Next Chapter Recommendation
We've mastered routes, but what if we want to run a piece of code *before* the route executes? For example, checking if a user is logged in before allowing them to see a profile? This brings us to the most powerful concept in Express. In Chapter 15: Express.js Middleware, we will learn how to intercept requests!