Handling Incoming Data π₯
A web application is all about interaction. Clients send data to the server, and the server acts on it. Express makes it easy to access this incoming data through properties on the request (req) object.
There are three primary ways a client can send data, and Express provides a specific property for each:
req.params: For data passed in the URL path (Route Parameters).req.query: For data passed in the URLβs query string.req.body: For data sent in the request body (payload).
req.params - For Route Parameters
Route parameters are used to capture values from specific, dynamic segments of the URL path. They are perfect for identifying a specific resource.
You define a route parameter by prefixing it with a colon (:) in your route path. Express then populates the req.params object with these values.
const express = require("express");
const app = express();
// The ':productId' is a route parameter.
app.get("/products/:productId/reviews/:reviewId", (req, res) => {
// req.params will be an object like { productId: '...', reviewId: '...' }
const { productId, reviewId } = req.params;
res.send(`You are viewing review #${reviewId} for product #${productId}.`);
});
app.listen(3000);
// Visiting http://localhost:3000/products/101/reviews/45 will set
// req.params to { productId: '101', reviewId: '45' }req.query - For URL Query Strings
Query strings are key-value pairs appended to the end of a URL after a ?. They are typically used for optional data, like filtering, sorting, or pagination. Express automatically parses the query string into the req.query object.
const express = require("express");
const app = express();
app.get("/search", (req, res) => {
// For a URL like /search?term=javascript&sort=popular
// req.query will be { term: 'javascript', sort: 'popular' }
const { term, sort } = req.query;
if (!term) {
return res.status(400).send("Search term is required.");
}
res.send(`Searching for "${term}" and sorting by "${sort || "relevance"}".`);
});
app.listen(3000);
// Visit http://localhost:3000/search?term=express&sort=newestreq.body - For the Request Payload
The request body is used to send more complex or larger amounts of data, typically with POST, PUT, or PATCH requests. This is how youβd send JSON data for an API or data from an HTML form.
β οΈ Important: By default, req.body is undefined. You must use a body-parsing middleware to populate it. Express has built-in middleware for this.
express.json(): Parses incoming requests with JSON payloads (Content-Type: application/json).express.urlencoded({ extended: true }): Parses incoming requests with URL-encoded payloads (standard web forms).
const express = require("express");
const app = express();
// MIDDLEWARE: This line is crucial for parsing JSON request bodies.
app.use(express.json());
app.post("/users", (req, res) => {
// Thanks to the middleware, req.body contains the parsed JSON data.
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).send("Username and password are required.");
}
// In a real app, you would save this to a database.
console.log("Creating new user:", req.body);
res.status(201).send(`User ${username} created successfully.`);
});
app.listen(3000);
// To test, use a tool like Postman or curl to send a POST request
// with a JSON body like: { "username": "alice", "password": "123" }β¨ Summary
req.params: For required identifiers in the URL path (e.g.,/products/:id).req.query: For optional data in the URL for filtering or sorting (e.g.,/products?category=laptops).req.body: For sending complex or sensitive data in the request payload (e.g., user signup forms).- Remember, using
req.bodyrequires you to set up body-parsing middleware likeexpress.json().