Request & Response Objects
Express enhances Node's raw `req` and `res` objects with convenient helper methods and properties for reading requests and sending responses.
Understanding these objects is essential for building any route handler.
Request object
`req.params`, `req.query`, `req.body`, and `req.headers` give access to route parameters, query strings, parsed body data, and headers respectively.
Response object
`res.send()`, `res.json()`, `res.status()`, and `res.redirect()` are common ways to shape and send a response.
app.get('/greet', (req, res) => {
const name = req.query.name || 'Guest';
res.status(200).send('Hello, ' + name);
});Hello, Guestreq.query reads URL query parameters; res.status().send() sends a status and body.
app.post('/users', express.json(), (req, res) => {
res.json({ received: req.body });
});{"received":{"name":"Ada"}}req.body contains the parsed JSON body when express.json() middleware is used.
Key points
- req.params, req.query, req.body access different request data.
- res.send/json/status/redirect shape the response.
- res.status() sets the HTTP status code.
- Chaining like res.status(404).send() is common in Express.
