Creating an Express Server
Objectives
By the end of this lesson, you should be able to:
- Install Express and create a minimal server
- Define a route and send a response
- Explain what Express adds on top of Node’s raw
httpmodule
💡 Why this matters: Module 4 built a server with
http.createServerand manualif/else ifrouting. Express replaces that entire manual routing setup with a small, expressive API, this is why it’s the most widely used Node.js web framework.
⚠️ A note on verification: every snippet and every response shown below was actually run and tested with real HTTP requests, using Express 5.
Installing Express
npm init -y
npm install express
{
"dependencies": {
"express": "^5.2.1"
}
}
Express installs like any other npm package (Module 3). It’s a regular dependency in package.json, nothing special about how it’s added to a project.
A Minimal Server
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Welcome to the homepage');
});
app.listen(4001, () => {
console.log('server listening on port 4001');
});
server listening on port 4001
curl http://localhost:4001/
Welcome to the homepage
express() creates an application object, conventionally called app. app.get(path, handler) registers a handler for GET requests to path, the handler receives a request object (req) and a response object (res), covered in detail in Lesson 3. res.send(body) sends a response and ends it, roughly Express’s version of http’s res.writeHead() + res.end() combined into one call, with the Content-Type header set automatically based on what’s sent.
app.listen(port, callback) starts the server, identical in purpose to http’s server.listen() from Module 4.
What Express Adds
Compared to the raw http module from Module 4, Express provides: a routing system matching URLs and methods to handlers, without manual if/else if chains (Lesson 2), convenient methods for reading request data (Lesson 3, 4, 5), built-in helpers for sending JSON and setting status codes (Lesson 7), and a middleware system (Module 7) for sharing logic like authentication or logging across many routes. Every one of these still runs on top of Node’s own http module under the hood, Express is a layer, not a replacement.
Try It
- Install Express in a new project and create a server with a single route at
/returning any plain text message. - Start the server and confirm it responds correctly using
curl. - Add a second route at
/pingthat responds with the text"pong". - Explain, in your own words, what
app.listen()andres.send()each do.
Recap
npm install express, thenexpress()creates an app,app.get(path, handler)registers a route,app.listen(port)starts the server.res.send(body)sends a response, settingContent-Typeautomatically.- Express is a layer on top of Node’s
httpmodule, replacing manual routing and response handling with a much smaller API.
Next lesson: routing, matching multiple URLs and HTTP methods to their handlers.