Node.js Express
Express is the most popular web framework for Node.js. It makes routing, reading data and sending responses short and simple.
Installing Express
Example
mkdir course-api
cd course-api
npm init -y
npm install expressAdd "type": "module" to package.json so you can use import. This installs Express 5, the current major version.
A First Express Server
Create index.js:
Example
import express from "express";
const app = express();
const PORT = process.env.PORT || 3000;
app.get("/", (req, res) => {
res.send("Welcome to the Workownix course API");
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});Example
node --watch index.jsServer running on http://localhost:3000
Compare this with the plain http server: no writeHead, no URL checks. res.send() sets the content type and ends the response for you.
Routes
A route is a method plus a path:
| Method | Usual job | Example |
|---|---|---|
app.get | Read data | GET /api/courses |
app.post | Create data | POST /api/courses |
app.put / app.patch | Update data | PATCH /api/courses/2 |
app.delete | Delete data | DELETE /api/courses/2 |
A Small REST API
Example
import express from "express";
const app = express();
app.use(express.json()); // read JSON bodies
let courses = [
{ id: 1, name: "Web Development", months: 6 },
{ id: 2, name: "Graphic Designing", months: 3 },
];
// List all courses, with an optional search: /api/courses?q=web
app.get("/api/courses", (req, res) => {
const q = (req.query.q || "").toLowerCase();
res.json(courses.filter((c) => c.name.toLowerCase().includes(q)));
});
// Get one course: /api/courses/2
app.get("/api/courses/:id", (req, res) => {
const course = courses.find((c) => c.id === Number(req.params.id));
if (!course) return res.status(404).json({ error: "Course not found" });
res.json(course);
});
// Add a course
app.post("/api/courses", (req, res) => {
const { name, months } = req.body;
if (!name) return res.status(400).json({ error: "Name is required" });
const course = { id: courses.length + 1, name, months: Number(months) || 1 };
courses.push(course);
res.status(201).json(course);
});
// Delete a course
app.delete("/api/courses/:id", (req, res) => {
courses = courses.filter((c) => c.id !== Number(req.params.id));
res.status(204).end();
});
app.listen(3000, () => console.log("API ready on port 3000"));A request to GET /api/courses/2 returns:
{"id":2,"name":"Graphic Designing","months":3}| Where the data is | How to read it | Example URL or body |
|---|---|---|
| Route parameter | req.params.id | /api/courses/2 |
| Query string | req.query.q | /api/courses?q=web |
| JSON body | req.body.name | {"name": "AI"} (needs express.json()) |
Here the data lives in an array, so it is lost when the server restarts. Real apps save it in a database such as MongoDB, MySQL or PostgreSQL.
Middleware
Middleware is a function that runs before your routes. It receives req, res and next, and calls next() to pass control on.
Example
app.use((req, res, next) => {
console.log(new Date().toLocaleTimeString(), req.method, req.url);
next();
});10:42:05 AM GET /api/courses 10:42:09 AM POST /api/courses
Common uses of middleware:
express.json()to read JSON bodiesexpress.static("public")to serve HTML, CSS and image files from a folder- Checking if a user is logged in
- Logging and error handling
Serving a Website
Put index.html and other files in a public folder and add:
Example
app.use(express.static("public"));Now http://localhost:3000/ shows public/index.html, and your front end can call the API with fetch("/api/courses").
Handling Errors
An error-handling middleware has four parameters and goes after all routes:
Example
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ error: "Something went wrong on the server" });
});In Express 5, errors thrown inside async route handlers are sent to this handler automatically.
Test your API with a tool like Postman, Thunder Client (a VS Code extension) or curl. Browsers can only send GET requests from the address bar.
Exercise
Exercise
Which line lets Express read JSON data sent in a POST request body?
