Express.js Basics
Express.js is the most popular Node.js web framework. It gives you a clean API for building web servers and APIs without reinventing the wheel.
Setting Up Express
npm install express
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("Hello from Express!");
});
app.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
Try it Yourself โ
Middleware
Middleware functions have access to the request, response, and next function. They run before route handlers:
// Built-in middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Custom middleware
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next(); // Pass control to next middleware
});
// Static files
app.use(express.static("public"));
Key Concept: Middleware is the most powerful feature of Express. Authentication, logging, CORS, body parsing โ they are all middleware. You can even write your own.
Serving JSON APIs
app.get("/api/users", (req, res) => {
res.json([
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" }
]);
});
app.post("/api/users", (req, res) => {
const { name, email } = req.body;
// Save to database...
res.status(201).json({ id: 3, name, email });
});