Node.js Tutorial menu

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

bash
mkdir course-api
cd course-api
npm init -y
npm install express

Add "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

js
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

bash
node --watch index.js
Output
Server 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:

MethodUsual jobExample
app.getRead dataGET /api/courses
app.postCreate dataPOST /api/courses
app.put / app.patchUpdate dataPATCH /api/courses/2
app.deleteDelete dataDELETE /api/courses/2

A Small REST API

Example

js
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:

Output
{"id":2,"name":"Graphic Designing","months":3}
Where the data isHow to read itExample URL or body
Route parameterreq.params.id/api/courses/2
Query stringreq.query.q/api/courses?q=web
JSON bodyreq.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

js
app.use((req, res, next) => {
  console.log(new Date().toLocaleTimeString(), req.method, req.url);
  next();
});
Output
10:42:05 AM GET /api/courses
10:42:09 AM POST /api/courses

Common uses of middleware:

  • express.json() to read JSON bodies
  • express.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

js
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

js
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?

Learn Node.js with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp