Lesson 53 of 55
javascriptExpress.js Fundamentals
15 mins
Course progress96%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 53 of 55
javascript15 mins
Keep these ideas in mind as you work through the lesson.
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.
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.
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.
// 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' });
});
app.use('/static', express.static('public'));
All files in the public folder are served under /static.
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.