Node.js ยท Chapter 20 of 43

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.

Example 1 (javascript)
app.get('/greet', (req, res) => {
  const name = req.query.name || 'Guest';
  res.status(200).send('Hello, ' + name);
});
Output
Hello, Guest

req.query reads URL query parameters; res.status().send() sends a status and body.

Example 2 (javascript)
app.post('/users', express.json(), (req, res) => {
  res.json({ received: req.body });
});
Output
{"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.
๐Ÿ’ก Note: Always validate req.body and req.query before trusting their contents.

๐Ÿ“ Quick Quiz

1. Which property holds parsed JSON body data?

2. Which method sets the HTTP status code on a response?

3. Which property reads query string parameters?