TExcelTAD
Home › Express & NestJS › Request & Response Objects

Request & Response Objects

Every handler receives two objects: req describes what the client sent, and res is how you answer. They are Node's own IncomingMessage and ServerResponse, extended by Express with convenient properties and methods.

The request: req

Property / method Example value Meaning
req.method 'POST' HTTP verb
req.path '/books/7' path without the query string
req.originalUrl '/api/books/7?x=1' full URL as received (unchanged by routers)
req.params { id: '7' } path parameters
req.query { x: '1' } parsed query string
req.body { title: 'Dune' } parsed body — only after a body-parser middleware
req.get(name) req.get('content-type') read a header (case-insensitive)
req.headers { 'user-agent': '…' } all headers, lower-cased keys
req.ip '::1' client address
req.is(type) req.is('json') does the body have this content type?
req.accepts(types) req.accepts(['json', 'html']) best match from the Accept header
node · try it yourself
const express = require('express');

const app = express();

app.get('/inspect/:id', (req, res) => {
  res.json({
    method: req.method,
    path: req.path,
    originalUrl: req.originalUrl,
    params: req.params,
    query: req.query,
    agent: req.get('User-Agent'),
    wantsJson: req.accepts(['html', 'json']),
  });
});

const server = app.listen(0, async () => {
  const res = await fetch(`http://localhost:${server.address().port}/inspect/7?verbose=yes`, {
    headers: { 'User-Agent': 'course-client/1.0', Accept: 'application/json' },
  });
  console.log(await res.json());
  server.close();
});
{
  method: 'GET',
  path: '/inspect/7',
  originalUrl: '/inspect/7?verbose=yes',
  params: { id: '7' },
  query: { verbose: 'yes' },
  agent: 'course-client/1.0',
  wantsJson: 'json'
}

Note: In Express 5, req.body is undefined until a parser such as express.json() runs. Code like req.body.title will throw if you forget the parser — use req.body?.title or validate first.

The response: res

Most res methods return res, so they can be chained: res.status(201).set('Location', '/books/3').json(book).

Method What it does
res.status(code) set the status code (Express 5 throws on invalid codes like 999 or '200')
res.set(name, value) / res.set({...}) set response headers
res.type('json') set Content-Type from a short name or extension
res.json(value) send JSON
res.send(body) send a string, Buffer or object
res.sendStatus(code) set the status and send its text, e.g. Not Found
res.redirect([status,] url) redirect (302 by default)
res.cookie(name, value, opts) add a Set-Cookie header
res.sendFile(absPath) stream a file with the right type
res.download(absPath) like sendFile but as an attachment
res.headersSent true once the response has started
node · try it yourself
const express = require('express');

const app = express();

app.post('/books', (req, res) => {
  res
    .status(201)
    .set('Location', '/books/3')
    .cookie('lastCreated', '3', { httpOnly: true })
    .json({ id: 3, title: 'Piranesi' });
});

app.get('/old-catalogue', (req, res) => res.redirect(301, '/books'));
app.get('/gone', (req, res) => res.sendStatus(410));

const server = app.listen(0, async () => {
  const base = `http://localhost:${server.address().port}`;

  const created = await fetch(base + '/books', { method: 'POST' });
  console.log(created.status, created.headers.get('location'), await created.text());
  console.log('set-cookie:', created.headers.get('set-cookie'));

  const moved = await fetch(base + '/old-catalogue', { redirect: 'manual' });
  console.log(moved.status, '->', moved.headers.get('location'));

  const gone = await fetch(base + '/gone');
  console.log(gone.status, await gone.text());
  server.close();
});
201 /books/3 {"id":3,"title":"Piranesi"}
set-cookie: lastCreated=3; Path=/; HttpOnly
301 -> /books
410 Gone

One response per request

You can only respond once. A second res.json() throws ERR_HTTP_HEADERS_SENT. The usual cause is forgetting return after an early response:

js
app.get('/user/:id', (req, res) => {
  if (!users.has(req.params.id)) {
    res.status(404).json({ error: 'not found' }); // missing "return"!
  }
  res.json(users.get(req.params.id)); // runs too → "Cannot set headers after they are sent"
});

Write return res.status(404).json(...) to stop the function there.

Content negotiation with res.format()

One endpoint can serve several formats depending on the client's Accept header:

node · try it yourself
const express = require('express');

const app = express();
const book = { id: 1, title: 'Dune' };

app.get('/book', (req, res) => {
  res.format({
    'application/json': () => res.json(book),
    'text/plain': () => res.send(`#${book.id} ${book.title}`),
    default: () => res.status(406).send('Not Acceptable'),
  });
});

const server = app.listen(0, async () => {
  const url = `http://localhost:${server.address().port}/book`;
  for (const accept of ['application/json', 'text/plain', 'image/png']) {
    const res = await fetch(url, { headers: { Accept: accept } });
    console.log(accept.padEnd(17), res.status, await res.text());
  }
  server.close();
});
application/json  200 {"id":1,"title":"Dune"}
text/plain        200 #1 Dune
image/png         406 Not Acceptable

Tip: res.locals is an object that lives for one request. Middleware can store data there (for example the logged-in user) for later handlers and templates.

Test yourself

Which property keeps the full URL even inside a mounted router?

  1. req.path
  2. req.url
  3. req.originalUrl
  4. req.baseUrl

What is req.body in Express 5 when no body-parsing middleware ran?

  1. {}
  2. ''
  3. undefined
  4. null

What causes the error "Cannot set headers after they are sent"?

  1. Calling res.status twice
  2. Sending a second response for the same request
  3. Using res.json with an array
  4. A missing Content-Type