Getting Started with Express
The framework that makes Node back-ends easy. Build a working server in just a few lines.
What you will learn
- Install and set up Express
- Create a basic server
- Send responses
Why Express?
Express is the most popular Node framework — the E in MERN. (A framework is a ready-made set of tools and shortcuts that does the repetitive plumbing for you, so you write far less code.) It handles routing, requests and responses with clean, simple code instead of the raw http boilerplate you saw earlier. (Boilerplate means the same dull setup code you would otherwise have to type by hand every time.) Since it is a package, you install it with npm first:
npm init -y
npm install expressNote: Output:
added 60-ish packages in 2s
npm init -y creates your package.json, and npm install express downloads Express (plus the smaller packages it relies on) into node_modules/. Now you can require("express") in your code.
Now the whole server in a handful of lines:
// server.js
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("<h1>Hello from Express!</h1>");
});
app.listen(3000, () => console.log("Running on http://localhost:3000"));Line by line: require("express") loads the framework, and express() creates your app (commonly named app). app.get("/", ...) says "when a browser asks for the home page /, run this function" — and res.send(...) sends a reply back. app.listen(3000, ...) starts the server on port 3000. Compare this to the raw http version: no writeHead, no manual headers — Express handles those for you.
node server.js
# Visit http://localhost:3000 → Hello from Express!Note: Output (in the terminal):
Running on http://localhost:3000
The server starts and stays listening. Open http://localhost:3000 in a browser and you see Hello from Express!. Express set the right HTML headers automatically because we passed HTML text to res.send.
Tip: Compare this to the raw http server from earlier — Express is far cleaner. That simplicity is why nearly every Node back-end uses it.
Q. What is Express?
✍️ Practice
- Set up an Express server that responds “Hello” at the home route.
- Add a
/aboutroute that sends some HTML.
🏠 Homework
- Build an Express server with three routes (/, /about, /contact), each sending different content.