Express: routes & middleware
Creating an Express app, route parameters, query strings, JSON bodies and middleware.
Express is the most widely used Node web framework. It adds clean routing and middleware on top of the http module.
- Routes:
app.get,app.post,app.put,app.deletewith a path and a handler(req, res). - Route parameters:
/jobs/:id→req.params.id. - Query strings:
/jobs?city=Kochi→req.query.city. - JSON body: add
app.use(express.json()), then readreq.body.
Middleware is a function (req, res, next) that runs before your routes — logging, authentication, parsing. It either sends a response or calls next() to pass control on.
Example code
Run with Node.js 20+// app.js (npm install express)
import express from "express";
const app = express();
app.use(express.json());
// middleware: log every request
app.use((req, res, next) => {
console.log(req.method, req.url);
next();
});
const jobs = [
{ id: 1, title: "Node.js Developer", city: "Kochi" },
{ id: 2, title: "QA Engineer", city: "Trivandrum" }
];
app.get("/jobs", (req, res) => {
const { city } = req.query;
res.json(city ? jobs.filter((j) => j.city === city) : jobs);
});
app.get("/jobs/:id", (req, res) => {
const job = jobs.find((j) => j.id === Number(req.params.id));
if (!job) return res.status(404).json({ error: "Job not found" });
res.json(job);
});
app.listen(3000, () => console.log("API on http://localhost:3000"));
Output
API on http://localhost:3000
GET /jobs?city=Kochi
GET /jobs/9
$ curl "http://localhost:3000/jobs?city=Kochi"
[{"id":1,"title":"Node.js Developer","city":"Kochi"}]
$ curl http://localhost:3000/jobs/9
{"error":"Job not found"}
Save the code in a file such as app.js and run node app.js. For Express lessons, run npm install express first. Names and data are fictional.
Key points
- Express adds routing and middleware to Node.
- req.params for path values, req.query for ?filters, req.body for JSON.
- Middleware calls next() or sends a response.
- Return proper status codes such as 404.
Quick check
In /jobs/:id, how do you read the id?
Named path segments like :id are available on req.params. req.query holds ?key=value pairs.
Practice task
Add GET /jobs?q=node that returns jobs whose title contains the search word, ignoring upper/lower case.
Interview corner
What is middleware in Express?
A function with (req, res, next) that runs in order for matching requests. It can change the request, end the response, or call next() — used for logging, auth, validation, CORS and error handling.
What is the difference between app.use and app.get?
app.get handles only GET requests for a path. app.use mounts middleware (or a router) for every method on a path prefix.
Further reading
Official documentation, linked for deeper study. These are outside sites; this lesson's text is our own.
Original lesson written by the InfoparkDaily team · © 2026 InfoparkDaily · Free to learn — no paid course or subscription.