9. Express.js: основы

Express.js — самый популярный фреймворк для Node.js. Минималистичный, гибкий, с огромной экосистемой middleware.
Установка и первый сервер
Заголовок раздела «Установка и первый сервер»npm install expressnpm install -D nodemonconst express = require('express');
const app = express();
// Middleware для парсинга JSONapp.use(express.json());// Middleware для URL-encoded формapp.use(express.urlencoded({ extended: true }));
// Роутapp.get('/', (req, res) => { res.json({ message: 'Привет от Express!' });});
// Запуск сервераconst PORT = process.env.PORT || 3000;app.listen(PORT, () => { console.log(`Сервер запущен: http://localhost:${PORT}`);});Request объект
Заголовок раздела «Request объект»app.post('/api/users', (req, res) => { // Тело запроса (JSON, form-data) console.log(req.body); // { name: 'Яша', email: '...' }
// Параметры URL (/users/:id) console.log(req.params.id); // '42'
// Query параметры (?page=1&limit=10) console.log(req.query.page); // '1' console.log(req.query.limit); // '10'
// Заголовки console.log(req.headers['authorization']); // 'Bearer ...' console.log(req.get('Content-Type')); // 'application/json'
// IP клиента console.log(req.ip); // '127.0.0.1'
// Метод console.log(req.method); // 'POST'
// Полный URL console.log(req.url); // '/api/users' console.log(req.path); // '/api/users' console.log(req.originalUrl); // '/api/users'
// Хост console.log(req.hostname); // 'localhost' console.log(req.protocol); // 'http'
// Кастомные данные от middleware console.log(req.user); // { id: 1, name: 'Яша' }});Response объект
Заголовок раздела «Response объект»app.get('/examples', (req, res) => { // Отправить JSON res.json({ data: 'value' });
// Отправить статус + JSON res.status(201).json({ id: 1, name: 'Яша' });
// Отправить текст res.send('Обычный текст');
// Отправить HTML res.send('<h1>Привет!</h1>');
// Перенаправление res.redirect('/new-path'); res.redirect(301, '/permanent-redirect');
// Отправить файл res.sendFile('/absolute/path/to/file.pdf');
// Скачать файл res.download('/path/to/report.xlsx', 'отчёт.xlsx');
// Установить заголовок res.set('X-Custom-Header', 'value'); res.set({ 'X-A': '1', 'X-B': '2' });
// Установить cookie res.cookie('token', 'abc123', { httpOnly: true, maxAge: 86400000 }); res.clearCookie('token');
// Только статус без тела res.sendStatus(204); // No Content
// Завершить соединение res.end();});Структура приложения
Заголовок раздела «Структура приложения»src/├── index.js # Точка входа, запуск сервера├── app.js # Конфигурация Express├── routes/ # Роуты│ ├── index.js # Главный роутер│ ├── users.js # /users роуты│ └── auth.js # /auth роуты├── controllers/ # Логика обработчиков│ ├── users.js│ └── auth.js├── middleware/ # Middleware│ ├── auth.js│ └── errorHandler.js├── models/ # Модели данных└── config/ # Конфигурация// src/app.js — конфигурация Expressconst express = require('express');const cors = require('cors');const usersRouter = require('./routes/users');const authRouter = require('./routes/auth');const { errorHandler } = require('./middleware/errorHandler');
const app = express();
// Middlewareapp.use(cors());app.use(express.json({ limit: '10mb' }));app.use(express.urlencoded({ extended: true }));
// Роутыapp.use('/api/users', usersRouter);app.use('/api/auth', authRouter);
// Обработка 404app.use((req, res) => { res.status(404).json({ error: 'Route not found' });});
// Обработчик ошибок (последний!)app.use(errorHandler);
module.exports = app;// src/index.js — точка входаrequire('dotenv').config();const app = require('./app');
const PORT = process.env.PORT || 3000;const server = app.listen(PORT, () => { console.log(`🚀 Сервер на порту ${PORT}`);});
// Graceful shutdownprocess.on('SIGTERM', () => { server.close(() => { console.log('Сервер остановлен'); process.exit(0); });});Статические файлы
Заголовок раздела «Статические файлы»const path = require('path');
// Отдавать файлы из папки public/app.use(express.static(path.join(__dirname, 'public')));
// С URL префиксомapp.use('/static', express.static(path.join(__dirname, 'public')));
// С настройками кэшированияapp.use(express.static('public', { maxAge: '1d', // кэш на 1 день etag: false,}));Шаблонизаторы
Заголовок раздела «Шаблонизаторы»const path = require('path');
// EJS шаблонизаторapp.set('view engine', 'ejs');app.set('views', path.join(__dirname, 'views'));
app.get('/dashboard', (req, res) => { res.render('dashboard', { title: 'Панель управления', user: { name: 'Яша' }, tasks: [{ id: 1, title: 'Задача 1' }], });});Практика
Заголовок раздела «Практика»- Создай Express приложение со структурой
app.js+index.js - Добавь GET
/api/products— возвращает массив товаров - Добавь POST
/api/products— принимает JSON и возвращает созданный товар - Подключи раздачу статических файлов из папки
public/ - Добавь обработчик 404 для всех несуществующих роутов