You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Express is the most popular web framework for Node.js. It wraps the built-in http module with a clean, minimal API for routing, middleware, and request/response handling.
npm install express
const express = require("express");
const app = express();
const PORT = 3000;
app.get("/", function (req, res) {
res.send("Hello from Express!");
});
app.listen(PORT, function () {
console.log("Server listening on port " + PORT);
});
express() returns an application object. You define routes on it using methods that match HTTP verbs: app.get(), app.post(), app.put(), app.delete(), and so on.
Express adds convenient helper methods to the response object:
// Send a plain string
res.send("Hello!");
// Send JSON automatically (sets Content-Type header)
res.json({ message: "Success", data: [] });
// Send an HTTP status code and JSON
res.status(404).json({ error: "Not found" });
// Send an HTML file
res.sendFile("/absolute/path/to/index.html");
app.use(express.json()); // parse JSON request bodies
app.use(express.urlencoded({ extended: true })); // parse form data
app.post("/users", function (req, res) {
const { name, email } = req.body; // parsed body
const search = req.query.filter; // ?filter=active
console.log(req.headers["content-type"]);
res.status(201).json({ name, email });
});
app.get("/users/:id", function (req, res) {
const userId = req.params.id; // e.g. '42' from /users/42
res.json({ userId });
});
Serve an entire folder of static assets (HTML, CSS, images) with one line:
app.use(express.static("public"));
Files in the public/ directory are then accessible at the root URL.
| Task | Raw http | Express |
|---|---|---|
| Route by URL and method | Manual if/else | app.get('/path', handler) |
| Parse JSON body | Manual stream collection | express.json() middleware |
| Send JSON response | Manual headers + JSON.stringify | res.json(data) |
| Serve static files | Manual | express.static('public') |
Express dramatically reduces boilerplate and is flexible enough to power anything from a simple REST API to a full-stack web application. The next lessons explore routing and middleware in greater depth.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.