Module 1 · Our first Express application
1.2 Routes, requests and responses
Return maintenance issues as JSON, read route parameters and query strings, choose status codes, and let Node restart the server for you.
Starting point
You have an Express server that answers GET / with a line of text:
caretaker/├── package.json (type: module, start script)└── src/ └── server.jsOutcome
Our server gains a tiny, hard-coded list of maintenance issues and three behaviours:
| Request | Response |
|---|---|
GET /api/issues |
200 and all issues as JSON |
GET /api/issues?status=open |
200 and only open issues |
GET /api/issues/2 |
200 and issue 2 |
GET /api/issues/99 |
404 and a JSON error |
We also add npm run dev, which restarts the server every time you save a file.
The problem
At the end of the last lesson we had to stop and start the server by hand after each change. That gets old fast. More importantly, our app needs to answer questions about specific records ("show me issue 2") and filtered lists ("only open issues"). Those details travel in the URL, and we need to know exactly where Express puts them.
Build it
1. A development script that restarts on save
Node.js has a built-in file watcher. node --watch restarts the process whenever a file it loaded changes. Add a second script:
npm pkg set scripts.dev="node --watch src/server.js"
From now on use npm run dev while you build. npm start stays the "run it once, no watching" command.
2. Some data to serve
We do not have a database yet. A plain array is enough to learn routing. Add it to src/server.js, below the port line:
const port = 3000; const issues = [ { id: 1, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', building: 'Dublin Offices', occurredAt: '2026-11-02T09:15:00.000Z' }, { id: 2, title: 'Dripping tap in the second-floor kitchen', priority: 'medium', status: 'closed', building: 'Dublin Offices', occurredAt: '2026-11-05T14:40:00.000Z' }, { id: 3, title: 'Front door lock sticks at entrance 4', priority: 'critical', status: 'open', building: 'Cork Apartments', occurredAt: '2026-11-08T07:05:00.000Z' },];
Show the whole src/server.js after this change
import express from 'express'; const app = express();const port = 3000; const issues = [ { id: 1, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', building: 'Dublin Offices', occurredAt: '2026-11-02T09:15:00.000Z' }, { id: 2, title: 'Dripping tap in the second-floor kitchen', priority: 'medium', status: 'closed', building: 'Dublin Offices', occurredAt: '2026-11-05T14:40:00.000Z' }, { id: 3, title: 'Front door lock sticks at entrance 4', priority: 'critical', status: 'open', building: 'Cork Apartments', occurredAt: '2026-11-08T07:05:00.000Z' },]; app.get('/', (req, res) => { res.send('Caretaker is running');}); app.listen(port, () => { console.log(`Caretaker listening on http://localhost:${port}`);});import express from 'express';
const app = express();
const port = 3000;
const issues = [
{ id: 1, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', building: 'Dublin Offices', occurredAt: '2026-11-02T09:15:00.000Z' },
{ id: 2, title: 'Dripping tap in the second-floor kitchen', priority: 'medium', status: 'closed', building: 'Dublin Offices', occurredAt: '2026-11-05T14:40:00.000Z' },
{ id: 3, title: 'Front door lock sticks at entrance 4', priority: 'critical', status: 'open', building: 'Cork Apartments', occurredAt: '2026-11-08T07:05:00.000Z' },
];
app.get('/', (req, res) => {
res.send('Caretaker is running');
});
app.listen(port, () => {
console.log(`Caretaker listening on http://localhost:${port}`);
});
Each issue is a plain object. occurredAt is an ISO 8601 string in UTC (the Z means UTC). Dates travel as strings in JSON, so we store them that way for now.
3. List issues as JSON
Add a route after the GET / route:
res.send('Caretaker is running');}); app.get('/api/issues', (req, res) => { const { status } = req.query; const result = status ? issues.filter((issue) => issue.status === status) : issues; res.json(result);});
Show the whole src/server.js after this change
import express from 'express'; const app = express();const port = 3000; const issues = [ { id: 1, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', building: 'Dublin Offices', occurredAt: '2026-11-02T09:15:00.000Z' }, { id: 2, title: 'Dripping tap in the second-floor kitchen', priority: 'medium', status: 'closed', building: 'Dublin Offices', occurredAt: '2026-11-05T14:40:00.000Z' }, { id: 3, title: 'Front door lock sticks at entrance 4', priority: 'critical', status: 'open', building: 'Cork Apartments', occurredAt: '2026-11-08T07:05:00.000Z' },]; app.get('/', (req, res) => { res.send('Caretaker is running');}); app.get('/api/issues', (req, res) => { const { status } = req.query; const result = status ? issues.filter((issue) => issue.status === status) : issues; res.json(result);}); app.listen(port, () => { console.log(`Caretaker listening on http://localhost:${port}`);});import express from 'express';
const app = express();
const port = 3000;
const issues = [
{ id: 1, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', building: 'Dublin Offices', occurredAt: '2026-11-02T09:15:00.000Z' },
{ id: 2, title: 'Dripping tap in the second-floor kitchen', priority: 'medium', status: 'closed', building: 'Dublin Offices', occurredAt: '2026-11-05T14:40:00.000Z' },
{ id: 3, title: 'Front door lock sticks at entrance 4', priority: 'critical', status: 'open', building: 'Cork Apartments', occurredAt: '2026-11-08T07:05:00.000Z' },
];
app.get('/', (req, res) => {
res.send('Caretaker is running');
});
app.get('/api/issues', (req, res) => {
const { status } = req.query;
const result = status ? issues.filter((issue) => issue.status === status) : issues;
res.json(result);
});
app.listen(port, () => {
console.log(`Caretaker listening on http://localhost:${port}`);
});
req.queryis an object built from the query string, the part of the URL after?. For/api/issues?status=openit is{ status: 'open' }. When there is no query string it is{}, sostatusisundefinedand we return everything.res.json(value)convertsvalueto JSON withJSON.stringify, setsContent-Type: application/json; charset=utf-8, and sends it.
We put JSON routes under /api/ so they do not clash with the HTML pages we add in lesson 1.4.
4. One issue by ID
Add the route for a single issue below the list route:
res.json(result);}); app.get('/api/issues/:id', (req, res) => { const id = Number(req.params.id); const issue = issues.find((e) => e.id === id); if (!issue) { return res.status(404).json({ error: 'Issue not found' }); } res.json(issue);});
Show the whole src/server.js after this change
import express from 'express'; const app = express();const port = 3000; const issues = [ { id: 1, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', building: 'Dublin Offices', occurredAt: '2026-11-02T09:15:00.000Z' }, { id: 2, title: 'Dripping tap in the second-floor kitchen', priority: 'medium', status: 'closed', building: 'Dublin Offices', occurredAt: '2026-11-05T14:40:00.000Z' }, { id: 3, title: 'Front door lock sticks at entrance 4', priority: 'critical', status: 'open', building: 'Cork Apartments', occurredAt: '2026-11-08T07:05:00.000Z' },]; app.get('/', (req, res) => { res.send('Caretaker is running');}); app.get('/api/issues', (req, res) => { const { status } = req.query; const result = status ? issues.filter((issue) => issue.status === status) : issues; res.json(result);}); app.get('/api/issues/:id', (req, res) => { const id = Number(req.params.id); const issue = issues.find((e) => e.id === id); if (!issue) { return res.status(404).json({ error: 'Issue not found' }); } res.json(issue);}); app.listen(port, () => { console.log(`Caretaker listening on http://localhost:${port}`);});import express from 'express';
const app = express();
const port = 3000;
const issues = [
{ id: 1, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', building: 'Dublin Offices', occurredAt: '2026-11-02T09:15:00.000Z' },
{ id: 2, title: 'Dripping tap in the second-floor kitchen', priority: 'medium', status: 'closed', building: 'Dublin Offices', occurredAt: '2026-11-05T14:40:00.000Z' },
{ id: 3, title: 'Front door lock sticks at entrance 4', priority: 'critical', status: 'open', building: 'Cork Apartments', occurredAt: '2026-11-08T07:05:00.000Z' },
];
app.get('/', (req, res) => {
res.send('Caretaker is running');
});
app.get('/api/issues', (req, res) => {
const { status } = req.query;
const result = status ? issues.filter((issue) => issue.status === status) : issues;
res.json(result);
});
app.get('/api/issues/:id', (req, res) => {
const id = Number(req.params.id);
const issue = issues.find((e) => e.id === id);
if (!issue) {
return res.status(404).json({ error: 'Issue not found' });
}
res.json(issue);
});
app.listen(port, () => {
console.log(`Caretaker listening on http://localhost:${port}`);
});
:idin the path is a route parameter. Express matches any single path segment there and stores it inreq.params.id.- Route parameters are strings, just like environment variables.
req.params.idfor/api/issues/2is"2". Our IDs are numbers, and"2" === 2is false, so we convert withNumber(...). res.status(404)sets the status code and returnsres, so we can chain.json(...).returnstops the function. Without it the code would continue to the secondres.jsonand Express would throwERR_HTTP_HEADERS_SENT, because a response can only be sent once.
Run and inspect
Start the development server. Leave it running in its own terminal:
npm run dev
> caretaker@1.0.0 dev
> node --watch src/server.js
Caretaker listening on http://localhost:3000
In your second terminal, list everything. -s hides curl's progress output; -i shows the headers:
curl -i http://localhost:3000/api/issues
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 485
ETag: W/"1e5-xCwuazerKpUB+vcdVD3oycp4/Oo"
Date: Sat, 28 Nov 2026 14:39:04 GMT
Connection: keep-alive
Keep-Alive: timeout=5
[{"id":1,"title":"Lift stuck between floors 2 and 3","priority":"high","status":"open","building":"Dublin Offices","occurredAt":"2026-11-02T09:15:00.000Z"},{"id":2,"title":"Dripping tap in the second-floor kitchen","priority":"medium","status":"closed","building":"Dublin Offices","occurredAt":"2026-11-05T14:40:00.000Z"},{"id":3,"title":"Front door lock sticks at entrance 4","priority":"critical","status":"open","building":"Cork Apartments","occurredAt":"2026-11-08T07:05:00.000Z"}]
The body is one long line of JSON. That is normal: JSON does not need whitespace.
Filter with a query string. Quote the URL so your shell does not treat ? as a wildcard:
curl -s "http://localhost:3000/api/issues?status=open"
[{"id":1,"title":"Lift stuck between floors 2 and 3","priority":"high","status":"open","building":"Dublin Offices","occurredAt":"2026-11-02T09:15:00.000Z"},{"id":3,"title":"Front door lock sticks at entrance 4","priority":"critical","status":"open","building":"Cork Apartments","occurredAt":"2026-11-08T07:05:00.000Z"}]
Ask for one issue, then for one that does not exist:
curl -s http://localhost:3000/api/issues/2
{"id":2,"title":"Dripping tap in the second-floor kitchen","priority":"medium","status":"closed","building":"Dublin Offices","occurredAt":"2026-11-05T14:40:00.000Z"}
curl -i http://localhost:3000/api/issues/99
HTTP/1.1 404 Not Found
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 27
ETag: W/"1b-Dc1YAmxtykOPy6JCQNL+lsQHwe8"
Date: Sat, 28 Nov 2026 14:39:04 GMT
Connection: keep-alive
Keep-Alive: timeout=5
{"error":"Issue not found"}
Notice the difference from lesson 1.1. There, no route matched and Express sent its own HTML 404 page. Here our route did match, and our code decided the answer was 404 and wrote JSON. The status code is the same; who decided is different.
What is inside req?
Let's look at the request object for a moment. Add a temporary log line to the single-issue route:
app.get('/api/issues/:id', (req, res) => { console.log({ method: req.method, path: req.path, params: req.params, query: req.query, userAgent: req.get('user-agent') }); const id = Number(req.params.id);
Show the whole src/server.js after this change
import express from 'express'; const app = express();const port = 3000; const issues = [ { id: 1, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', building: 'Dublin Offices', occurredAt: '2026-11-02T09:15:00.000Z' }, { id: 2, title: 'Dripping tap in the second-floor kitchen', priority: 'medium', status: 'closed', building: 'Dublin Offices', occurredAt: '2026-11-05T14:40:00.000Z' }, { id: 3, title: 'Front door lock sticks at entrance 4', priority: 'critical', status: 'open', building: 'Cork Apartments', occurredAt: '2026-11-08T07:05:00.000Z' },]; app.get('/', (req, res) => { res.send('Caretaker is running');}); app.get('/api/issues', (req, res) => { const { status } = req.query; const result = status ? issues.filter((issue) => issue.status === status) : issues; res.json(result);}); app.get('/api/issues/:id', (req, res) => { console.log({ method: req.method, path: req.path, params: req.params, query: req.query, userAgent: req.get('user-agent') }); const id = Number(req.params.id); const issue = issues.find((e) => e.id === id); if (!issue) { return res.status(404).json({ error: 'Issue not found' }); } res.json(issue);}); app.listen(port, () => { console.log(`Caretaker listening on http://localhost:${port}`);});import express from 'express';
const app = express();
const port = 3000;
const issues = [
{ id: 1, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', building: 'Dublin Offices', occurredAt: '2026-11-02T09:15:00.000Z' },
{ id: 2, title: 'Dripping tap in the second-floor kitchen', priority: 'medium', status: 'closed', building: 'Dublin Offices', occurredAt: '2026-11-05T14:40:00.000Z' },
{ id: 3, title: 'Front door lock sticks at entrance 4', priority: 'critical', status: 'open', building: 'Cork Apartments', occurredAt: '2026-11-08T07:05:00.000Z' },
];
app.get('/', (req, res) => {
res.send('Caretaker is running');
});
app.get('/api/issues', (req, res) => {
const { status } = req.query;
const result = status ? issues.filter((issue) => issue.status === status) : issues;
res.json(result);
});
app.get('/api/issues/:id', (req, res) => {
console.log({ method: req.method, path: req.path, params: req.params, query: req.query, userAgent: req.get('user-agent') });
const id = Number(req.params.id);
const issue = issues.find((e) => e.id === id);
if (!issue) {
return res.status(404).json({ error: 'Issue not found' });
}
res.json(issue);
});
app.listen(port, () => {
console.log(`Caretaker listening on http://localhost:${port}`);
});
Save. node --watch restarts the server. Send a request with a query string:
curl -s "http://localhost:3000/api/issues/3?debug=yes"
{"id":3,"title":"Front door lock sticks at entrance 4","priority":"critical","status":"open","building":"Cork Apartments","occurredAt":"2026-11-08T07:05:00.000Z"}
Look at the server terminal:
Caretaker listening on http://localhost:3000
{
method: 'GET',
path: '/api/issues/3',
params: [Object: null prototype] { id: '3' },
query: [Object: null prototype] { debug: 'yes' },
userAgent: 'curl/8.7.1'
}
req.path does not include the query string. [Object: null prototype] means Express built params and query as objects without the usual Object.prototype, so a key such as __proto__ in a URL cannot change the behaviour of every object in your program. req.params came from the URL path, req.query from the part after ?, and req.get(...) reads a request header. All three are chosen by the client. Keep that in mind: anyone can send any value in any of them.
Remove the log line again:
console.log({ method: req.method, path: req.path, params: req.params, query: req.query, userAgent: req.get('user-agent') }); const id = Number(req.params.id);
Show the whole src/server.js after this change
import express from 'express'; const app = express();const port = 3000; const issues = [ { id: 1, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', building: 'Dublin Offices', occurredAt: '2026-11-02T09:15:00.000Z' }, { id: 2, title: 'Dripping tap in the second-floor kitchen', priority: 'medium', status: 'closed', building: 'Dublin Offices', occurredAt: '2026-11-05T14:40:00.000Z' }, { id: 3, title: 'Front door lock sticks at entrance 4', priority: 'critical', status: 'open', building: 'Cork Apartments', occurredAt: '2026-11-08T07:05:00.000Z' },]; app.get('/', (req, res) => { res.send('Caretaker is running');}); app.get('/api/issues', (req, res) => { const { status } = req.query; const result = status ? issues.filter((issue) => issue.status === status) : issues; res.json(result);}); app.get('/api/issues/:id', (req, res) => { const id = Number(req.params.id); const issue = issues.find((e) => e.id === id); if (!issue) { return res.status(404).json({ error: 'Issue not found' }); } res.json(issue);}); app.listen(port, () => { console.log(`Caretaker listening on http://localhost:${port}`);});import express from 'express';
const app = express();
const port = 3000;
const issues = [
{ id: 1, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', building: 'Dublin Offices', occurredAt: '2026-11-02T09:15:00.000Z' },
{ id: 2, title: 'Dripping tap in the second-floor kitchen', priority: 'medium', status: 'closed', building: 'Dublin Offices', occurredAt: '2026-11-05T14:40:00.000Z' },
{ id: 3, title: 'Front door lock sticks at entrance 4', priority: 'critical', status: 'open', building: 'Cork Apartments', occurredAt: '2026-11-08T07:05:00.000Z' },
];
app.get('/', (req, res) => {
res.send('Caretaker is running');
});
app.get('/api/issues', (req, res) => {
const { status } = req.query;
const result = status ? issues.filter((issue) => issue.status === status) : issues;
res.json(result);
});
app.get('/api/issues/:id', (req, res) => {
const id = Number(req.params.id);
const issue = issues.find((e) => e.id === id);
if (!issue) {
return res.status(404).json({ error: 'Issue not found' });
}
res.json(issue);
});
app.listen(port, () => {
console.log(`Caretaker listening on http://localhost:${port}`);
});
Experiment
What does GET /api/issues/abc return? Predict the status code first.
curl -i http://localhost:3000/api/issues/abc return, and why?curl -i http://localhost:3000/api/issues/abc
HTTP/1.1 404 Not Found
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 27
ETag: W/"1b-Dc1YAmxtykOPy6JCQNL+lsQHwe8"
Date: Sat, 28 Nov 2026 14:39:06 GMT
Connection: keep-alive
Keep-Alive: timeout=5
{"error":"Issue not found"}
Reveal Explanation
Number('abc') is NaN, and NaN is not equal to anything (not even itself), so find returns undefined and our route answers 404. That is acceptable here. In Module 2 we validate IDs before they reach SQL, and you will see why "it happens to work" is not good enough.
Try one more: does GET /api/issues?status=OPEN (upper case) find anything? Run it and explain the result to yourself.
curl -s "http://localhost:3000/api/issues?status=OPEN"
[]
The filter compares strings exactly, so OPEN matches nothing and we get an empty array, with status 200. An empty list is a valid answer.
Checkpoint
Your src/server.js should now contain the issues array and three routes. Compare it with the full file shown under the last edit above ("Show the whole src/server.js after this change").
Commit:
git add -A
git commit -m "Return maintenance issues as JSON"
[main 1bc4e2d] Return maintenance issues as JSON
2 files changed, 23 insertions(+), 1 deletion(-)
Symptom Cannot GET /api/issues/ (with a trailing slash) works, but /api/issue/1 does not
Paths must match exactly, apart from a trailing slash. Check the spelling: the route is /api/issues/:id, plural.
Symptom Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
A handler called res.json (or res.send) twice. Usually a missing return before the 404 response.
Symptom Nothing happens when I save
You started the server with npm start, which does not watch files. Stop it and run npm run dev.
Recap and next step
A route is a method plus a path pattern. Express gives the handler the parsed request: req.params from the path, req.query from the query string, headers through req.get. All of them are strings, and all of them come from the client. The handler chooses the status code and the body.
So far we can only read. Next we accept new issues with POST, which needs a request body, validation, and a plan for errors. That is where middleware comes in.
Open the checkpoint files for lesson 1.2 (separate page; only files from this lesson and earlier)