Express Basics
Routing, middleware, and JSON APIs with the Express framework
Skills taught: node.express-routing, node.express-middleware, node.express-json, node.express-static
Setting up Express routes and middleware
const express = require('express');
const app = express();
// Middleware — runs for every request
app.use(express.json()); // parse JSON request bodies
app.use(express.static('public')); // serve files from /public
app.use((req, res, next) => { // custom logger
console.log(`${req.method} ${req.url}`);
next(); // MUST call next() or the request hangs
});
// Routes
app.get('/', (req, res) => {
res.send('<h1>Welcome to my API</h1>');
});
app.get('/api/users', (req, res) => {
const { role } = req.query; // /api/users?role=admin
const users = [
{ id: 1, name: 'Alice', role: 'admin' },
{ id: 2, name: 'Bob', role: 'user' },
];
const filtered = role ? users.filter(u => u.role === role) : users;
res.json(filtered);
});
app.get('/api/users/:id', (req, res) => {
const id = parseInt(req.params.id);
const user = [{ id:1, name:'Alice' }, { id:2, name:'Bob' }].find(u => u.id === id);
if (!user) return res.status(404).json({ error: 'User not found' });
res.json(user);
});
app.post('/api/users', (req, res) => {
const { name, role } = req.body; // parsed by express.json()
if (!name) return res.status(400).json({ error: 'name is required' });
const newUser = { id: Date.now(), name, role: role || 'user' };
res.status(201).json(newUser);
});
// Error handling middleware (4 params)
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Internal server error' });
});
app.listen(3000, () => console.log('Listening on http://localhost:3000'));
Tip: Call next() in every middleware that isn't an endpoint. If you forget, the request hangs — no response is ever sent. This is the most common Express beginner mistake.
Frequently Asked Questions
What is the difference between app.use() and app.get()?
app.use(path, fn) registers middleware that matches any HTTP method on any path (or the given prefix). app.get(path, fn) only matches GET requests to that exact path. app.use() is for cross-cutting concerns (logging, auth, body parsing); app.get/post/put/delete are for specific endpoints. Note: app.use('/api', router) mounts a router at a prefix — it matches any method and any sub-path.