Express.js FundamentalsLesson 1.3
Express routing — defining GET, POST, PUT, DELETE routes
app.get, app.post, app.put, app.delete, HTTP verb semantics, route handlers, app.route chaining, REST conventions
HTTP Method Routing in Express
Express maps HTTP verbs directly to methods on the app object. Each method registers a handler for requests matching that verb and path.
Defining all four core routes
const express = require('express');
const app = express();
app.use(express.json());
let users = [{ id: 1, name: 'Alice' }];
app.get('/users', (req, res) => {
res.json(users);
});
app.post('/users', (req, res) => {
const user = { id: Date.now(), ...req.body };
users.push(user);
res.status(201).json(user);
});
app.put('/users/:id', (req, res) => {
const user = users.find(u => u.id === +req.params.id);
if (!user) return res.status(404).json({ error: 'Not found' });
Object.assign(user, req.body);
res.json(user);
});
app.delete('/users/:id', (req, res) => {
users = users.filter(u => u.id !== +req.params.id);
res.status(204).send();
});
app.listen(3000);Use app.route() to chain handlers for the same path and avoid repetition:
app.route('/users/:id')
.get((req, res) => { /* ... */ })
.put((req, res) => { /* ... */ })
.delete((req, res) => { /* ... */ });Always return correct status codes: 200 (OK), 201 (Created), 204 (No Content), 404 (Not Found).
