Request and Response Objects
Objectives
By the end of this lesson, you should be able to:
- Read a request’s method, path, headers, and body using
req - Set a response’s status code, headers, and body using
res - Parse a JSON request body with
express.json()
💡 Why this matters:
reqandresare the two objects every single route handler works with, in every Express application ever written. Everything else in this module (params, query strings, JSON responses) is really just reading from or writing to these two objects.
⚠️ A note on verification: every snippet and every response shown below was actually run and tested with real HTTP requests.
Reading From the Request Object
const express = require('express');
const app = express();
app.use(express.json());
app.post('/users', (req, res) => {
console.log('method:', req.method);
console.log('path:', req.path);
console.log('body:', req.body);
console.log('header:', req.get('Content-Type'));
res.status(201);
res.set('X-Custom-Header', 'demo-value');
res.json({ received: req.body, status: 'created' });
});
app.listen(4003);
curl -X POST http://localhost:4003/users \
-H "Content-Type: application/json" \
-d '{"name":"Priya","role":"admin"}'
Server-side logs:
method: POST
path: /users
body: { name: 'Priya', role: 'admin' }
header: application/json
Response received by the client:
{"received":{"name":"Priya","role":"admin"},"status":"created"}
req.method and req.path mirror what Module 4’s raw req.method/req.url provided. req.get(headerName) reads a specific request header. req.body holds the parsed request body, but only once express.json() middleware (Module 7 covers middleware in depth) is registered with app.use(), without it, req.body is undefined for a JSON request, this is one of the most common early Express mistakes.
Writing to the Response Object
res.status(code) sets the HTTP status code (chainable, res.status(201).json(...) is extremely common, covered fully in Lesson 7). res.set(headerName, value) sets a response header. res.json(data) sends data as JSON, automatically setting Content-Type: application/json and calling JSON.stringify() on it, this is the JSON-specific equivalent of res.send() from Lesson 1.
Try It
- Write a route that logs
req.method,req.path, andreq.headers['user-agent']for any incoming request. - Register
express.json(), then write aPOSTroute that logsreq.bodyand echoes it back withres.json(). - Remove the
express.json()middleware temporarily, send the same request, and confirmreq.bodyis nowundefined, then add it back. - Write a route using
res.status(200).set('X-Info', 'test').json({ ok: true }), and confirm withcurl -ithat both the status code and the custom header appear in the response.
Recap
reqprovides everything about the incoming request:.method,.path,.get(header), and.body(only populated once JSON-parsing middleware is registered).resbuilds the response:.status(code),.set(header, value),.json(data), all chainable.express.json()must be registered withapp.use()beforereq.bodywill contain a parsed JSON request body.
Next lesson: route parameters, capturing dynamic segments of a URL.