6. Express.js Framework
Why Use Express?
The raw HTTP module works, but it's tedious. You have to manually parse URLs, handle routing, and collect POST body chunks. Express does all of this for you. It's the most popular Node.js framework for a reason.
Your First Express Server
Express is a minimal web framework built on top of the HTTP module. It adds powerful routing and middleware capabilities. The syntax is much cleaner than the raw HTTP module.
const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello Express!'); }); app.listen(3000, () => { console.log('Server running on port 3000'); });
Try it: Compare this to the raw HTTP version. Notice how much shorter and clearer it is.
Route Parameters (req.params)
Route parameters are dynamic parts of the URL, like /users/:id. The colon tells Express to capture whatever value is in that position and put it into req.params. This is how you create RESTful APIs that respond to specific resources.
app.get('/users/:userId', (req, res) => { const id = req.params.userId; res.send(`User ID is: ${id}`); }); app.get('/products/:category/:productId', (req, res) => { const { category, productId } = req.params; res.send(`Category: ${category}, Product: ${productId}`); });
Try it: Visit /users/123 and /products/electronics/456.
Query Parameters (req.query)
Query parameters come after the ? in a URL, like /search?q=node&page=2. Express automatically parses them into req.query. They are used for filtering, sorting, and pagination.
app.get('/search', (req, res) => { const { q, page = 1, limit = 10 } = req.query; res.send(`Searching for "${q}", page ${page}, limit ${limit}`); });
Reading POST Data (req.body)
Express needs middleware to parse JSON bodies. The express.json() middleware reads the incoming request body, parses it as JSON, and attaches the result to req.body. Without this, req.body is undefined.
app.use(express.json()); app.post('/api/users', (req, res) => { const { name, email } = req.body; res.json({ message: `User ${name} created`, email }); });
Sending JSON (res.json)
res.json() automatically converts JavaScript objects to JSON and sets the correct Content-Type header to application/json. You can chain .status() before .json() to set the HTTP status code.
app.get('/api/user', (req, res) => { const user = { id: 1, name: 'Alice', email: 'alice@example.com' }; res.json(user); }); app.post('/api/data', (req, res) => { res.status(201).json({ created: true, id: 123 }); });
Using Express Router
Express Router allows you to group related routes into separate files. This keeps your server.js clean as your API grows. Each router is a mini-Express application that you can mount on a path prefix.
// routes/users.js const router = require('express').Router(); router.get('/', (req, res) => res.json([{ id: 1, name: 'Alice' }])); router.post('/', (req, res) => res.status(201).json(req.body)); module.exports = router; // server.js const userRoutes = require('./routes/users'); app.use('/api/users', userRoutes);
Knowledge Check
Ready to test your understanding of 6. Express.js Framework?