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
| req | res |
|---|---|
| params — route :segments | status(code) — set HTTP status |
| query — ?key=value | json(obj) — JSON + Content-Type |
| body — parsed POST JSON | send(str) — body + end |
| headers, cookies | redirect(url) — 302/301 |
| method, path | set(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);