AceDevHub
Intermediate Node.js Interview QuestionsIntermediateConcept

Node.js · Question 45

What are Express request handlers?

Direct answer

Request handlers are (req, res, next) functions that read req (params, query, body, headers) and write res (status, json, send, redirect) — async handlers must catch errors or forward with next(err) to reach error middleware.

Handlers are the terminal or intermediate steps in the middleware chain — they implement business logic after parsers and auth run.

Why interviewers ask

reqres
params — route :segmentsstatus(code) — set HTTP status
query — ?key=valuejson(obj) — JSON + Content-Type
body — parsed POST JSONsend(str) — body + end
headers, cookiesredirect(url) — 302/301
method, pathset(header, value)
  • Async handlers — wrap await in try/catch and next(err), or use express-async-errors.
  • One response — calling res.json after res.send throws ERR_HTTP_HEADERS_SENT.
  • Fastify mapping — handler becomes route function; reply.code().send() parallels res.status().json().
express-handler.mjs
async function getTopic(req, res, next) {
  try {
    const { slug } = req.params;
    const page = Number(req.query.page ?? 1);
    // const topic = await interviewsService.getBySlug(slug, page);
    res.status(200).json({ slug, page });
  } catch (err) {
    next(err);
  }
}

// app.get('/interviews/topics/:slug', getTopic);