New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› Node.js› Express Fundamentals

Express Fundamentals

💻 Node.js

Use Express for routing, middleware and JSON request bodies.

Lesson 5 of 9 Tutorial
0 of 9 completed

Express is a small framework around Node HTTP. It removes repetitive routing code and adds middleware.

By the end of this lesson you can:
  • Create an Express app.
  • Handle routes and JSON bodies.
  • Write middleware.

A Basic App

Install Express, create an app, and listen on a port.

import express from "express";

const app = express();

app.get("/", (request, response) => {
  response.send("Hello from Express");
});

app.listen(3000, () => {
  console.log("Server running on port 3000");
});

JSON Bodies

Register express.json() before routes that read a JSON body.

app.use(express.json());

app.post("/students", (request, response) => {
  const { name, level } = request.body;

  if (!name) {
    return response.status(422).json({ error: "name is required" });
  }

  response.status(201).json({ id: 1, name, level });
});

Middleware

Middleware is a function that runs before the route. Use it for logging, authentication and error handling.

function logger(request, response, next) {
  console.log(request.method, request.url);
  next();
}

app.use(logger);
Warning Call next() in middleware or send a response. If you do neither, the request hangs.

Practice

  1. Create an Express app with two GET routes.
  2. Add express.json() and a POST route.
  3. Write middleware that adds a request time header.

Hands-on exercise

Build an Express app with:
1. GET /students returning an array of two students.
2. POST /students accepting name and level and returning 201.
3. A 422 response when name is missing.

Recap

Express adds routing, JSON parsing and middleware to Node. Register middleware before the routes that need it.

Example

import express from "express";

const app = express();

app.get("/", (request, response) => {
  response.send("Hello from Express");
});

app.listen(3000, () => {
  console.log("Server running on port 3000");
});

Exercises

Exercise 1. Students endpoint Medium
Build an Express app with:
1. GET /students returning an array of two students.
2. POST /students accepting name and level and returning 201.
3. A 422 response when name is missing.
Node.js exercise-1.txt
Expected Output
A list on GET and a created record on POST.

Lesson Nav

Lesson sections