Static routes are for basic websites. APIs require dynamic routing to handle infinite permutations of data requests and massive JSON payloads. In this lesson, we learn how to capture variables from the URL and parse data from the request body.
1The Power of `req.params`
When building a RESTful API, you don't create a distinct route for every user in your database. Instead, you define a scalable pattern.
By placing a colon (:) in the URL path (e.g., /products/:productId), you tell Express to catch whatever value is passed in that specific segment of the URL and store it as a dynamic variable. This variable becomes instantly accessible inside your route's callback function via the req.params object.
app.get('/users/:userId', (req, res) => {
const id = req.params.userId;
// Query database for user with this ID
});This is the exact mechanic Twitter uses to load your specific profile when you visit twitter.com/yourusername. The single route /users/:username handles millions of profiles.
async function execute() {
// See concept above
}
2The `req.body` Problem
While GET requests pass small amounts of data through the URL, POST and PUT requests require passing large data payloads (like a user registration form). This data is attached to the request 'Body'.
However, when data travels across the internet, it travels as a raw string of text. When this text hits your Express server, Express doesn't automatically assume it's JSON. If you attempt to read req.body.email in a brand new Express application, it will return undefined and crash your application.
Express requires explicit instructions on how to handle incoming string payloads.
async function execute() {
// See concept above
}
3Understanding Middleware
To instruct Express to parse JSON, we use Middleware.
Middleware is a function that has access to the Request and Response objects *before* they reach your final route callback. Think of it as a factory assembly line. A request comes in, the JSON middleware intercepts it and parses the body, an authentication middleware might verify a token, and *finally*, your specific app.post logic executes.
const express = require('express');
const app = express();
// The Assembly Line Middleware
app.use(express.json());
// The Route Callback
app.post('/users', (req, res) => {
console.log(req.body.email); // Now this works!
});The app.use(express.json()) command tells Express: 'Intercept every incoming request. If the request has a JSON string in its body, parse it into a native JavaScript object and attach it to req.body.' It is arguably the most important configuration line in any Node.js server.
async function execute() {
// See concept above
}
