Lesson 53 of 55 · javascript
Express.js Fundamentals
Duration: 15 mins
Express.js Fundamentals
Express is the de‑facto minimal web framework for Node.js. It helps you spin up HTTP servers quickly while keeping the core API tiny.
1️⃣ Install & scaffold
mkdir my‑api && cd my‑api
npm init -y
npm install express
Create index.js:
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server listening on http://localhost:${PORT}`));
Run with node index.js.
2️⃣ Routing
app.get('/', (req, res) => {
res.send('Welcome to the homepage!');
});
app.get('/api/users/:id', (req, res) => {
const user = { id: req.params.id, name: 'Alice' };
res.json(user);
});
Supported verbs: app.get, app.post, app.put, app.delete, etc.
3️⃣ Middleware
// built‑in JSON parser
app.use(express.json());
// simple logger middleware
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
Error‑handling middleware has four arguments:
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ error: 'Server error' });
});
4️⃣ Static files
app.use('/static', express.static('public'));
All files in the public folder are served under /static.
5️⃣ Simple API example
let todos = [{ id:1, title:'Learn Express', done:false }];
app.get('/api/todos', (req, res) => res.json(todos));
app.post('/api/todos', (req, res) => {
const newTodo = { id: Date.now(), ...req.body };
todos.push(newTodo);
res.status(201).json(newTodo);
});
Express is intentionally unopinionated – you can add templating engines, ORMs, authentication, etc., via a rich ecosystem of middleware.