Request & Response
The req and res objects every handler receives - reading data from requests, sending different response types, status codes, and headers.
What it is, in plain English: Every Express route handler and middleware function receives a request object (req) and a response object (res). req holds everything about the incoming request -- URL parameters, query string, headers, body, cookies. res provides methods to send a reply -- text, JSON, files, redirects, with control over status code and headers. These two objects are Express's enhanced wrappers around Node's raw IncomingMessage and ServerResponse.
Reading requests and sending responses
The request object -- everything about the incoming request
app.post("/users/:id", (req, res) => {
console.log(req.params); // URL parameters: { id: "42" }
console.log(req.query); // query string: ?key=value pairs
console.log(req.body); // parsed request body (needs express.json() middleware)
console.log(req.headers); // all request headers
console.log(req.method); // "POST"
console.log(req.url); // the full URL path + query string
});Sending different types of responses
// Plain text or HTML:
app.get("/", (req, res) => {
res.send("Hello, World!");
});
// JSON (the most common for APIs):
app.get("/api/user", (req, res) => {
res.json({ name: "Alice", age: 30 });
});
// With a specific status code:
app.post("/users", (req, res) => {
res.status(201).json({ created: true }); // 201 = Created
});
app.get("/users/:id", (req, res) => {
const user = findUser(req.params.id);
if (!user) {
return res.status(404).json({ error: "User not found" });
}
res.json(user);
});Status codes -- the standard set
Code
Meaning
When
200
OK
Successful GET/PUT
201
Created
Successful POST that created something
204
No Content
Successful DELETE
400
Bad Request
Client sent invalid data
401
Unauthorized
Missing/invalid authentication
403
Forbidden
Authenticated but not allowed
404
Not Found
Resource doesn't exist
500
Server Error
Something broke on your end
Redirects
app.get("/old-page", (req, res) => {
res.redirect("/new-page"); // 302 by default
// res.redirect(301, "/new-page"); // permanent redirect
});
Try It Yourself (Node.js logic)
Official Sources
The Codex links only to official documentation. No third-party tutorials.