Introduction to Express
Express is the most popular Node.js web framework. It simplifies routing, middleware, and request/response handling compared to the raw http module.
Install it with `npm install express`, then use it to build servers with far less boilerplate code.
Why Express?
Express provides a clean API for defining routes, handling middleware, parsing bodies, and serving static files, saving huge amounts of manual work.
A minimal app
An Express app is created with `express()`, routes are defined with methods like `.get()`, and the app starts with `.listen()`.
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello Express!');
});
app.listen(3000, () => console.log('Server running'));Server running
(GET / returns 'Hello Express!')Express dramatically reduces the code needed compared to raw http.
app.get('/json', (req, res) => {
res.json({ ok: true });
});{"ok":true}res.json() automatically sets headers and stringifies the object.
Key points
- Express is the most popular Node.js web framework.
- It simplifies routing and middleware handling.
- app.get(), app.post() etc. define routes for specific methods.
- res.json() sends a JSON response automatically.
