CodingNic

Express.js Fundamentals

Request and Response Objects

Express.js Fundamentals 12 min read

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: req and res are 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

javascript
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);
bash
curl -X POST http://localhost:4003/users \
  -H "Content-Type: application/json" \
  -d '{"name":"Priya","role":"admin"}'

Server-side logs:

text
method: POST
path: /users
body: { name: 'Priya', role: 'admin' }
header: application/json

Response received by the client:

text
{"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

  1. Write a route that logs req.method, req.path, and req.headers['user-agent'] for any incoming request.
  2. Register express.json(), then write a POST route that logs req.body and echoes it back with res.json().
  3. Remove the express.json() middleware temporarily, send the same request, and confirm req.body is now undefined, then add it back.
  4. Write a route using res.status(200).set('X-Info', 'test').json({ ok: true }), and confirm with curl -i that both the status code and the custom header appear in the response.

Recap

  • req provides everything about the incoming request: .method, .path, .get(header), and .body (only populated once JSON-parsing middleware is registered).
  • res builds the response: .status(code), .set(header, value), .json(data), all chainable.
  • express.json() must be registered with app.use() before req.body will contain a parsed JSON request body.

Next lesson: route parameters, capturing dynamic segments of a URL.