Як працює модуль HTTP у Node.js?
Модуль HTTP
Модуль http є основним модулем Node.js, який дозволяє створювати HTTP-сервери та виконувати HTTP-запити без зовнішніх залежностей. Це основа, на якій побудовані такі фреймворки, як Express.js.
Створення HTTP-сервера
js
const http = require('http');
const server = http.createServer((req, res) => {
// req = IncomingMessage (читабельний потік)
// res = ServerResponse (записуваний потік)
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Hello World' }));
});
server.listen(3000, () => {
console.log('Сервер працює на порту 3000');
});Об'єкт запиту (IncomingMessage)
js
const server = http.createServer((req, res) => {
console.log(req.method); // GET, POST, PUT, DELETE
console.log(req.url); // /api/users?page=1
console.log(req.headers); // { host: '...', 'content-type': '...' }
// Парсинг URL
const url = new URL(req.url, `http://${req.headers.host}`);
console.log(url.pathname); // /api/users
console.log(url.searchParams.get('page')); // '1'
});Обробка тіла POST-запиту
Тіло запиту надходить як потік — ви повинні збирати частини:
js
const server = http.createServer((req, res) => {
if (req.method === 'POST' && req.url === '/api/users') {
let body = '';
req.on('data', (chunk) => {
body += chunk.toString();
});
req.on('end', () => {
const data = JSON.parse(body);
res.writeHead(201, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ created: data }));
});
}
});Простий маршрутизатор
js
const server = http.createServer((req, res) => {
const { method, url } = req;
if (method === 'GET' && url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Головна</h1>');
} else if (method === 'GET' && url === '/api/users') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify([{ id: 1, name: 'John' }]));
} else {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Не знайдено' }));
}
});Виконання HTTP-запитів
js
const http = require('http');
// GET запит
http.get('http://api.example.com/data', (res) => {
let data = '';
res.on('data', (chunk) => data += chunk);
res.on('end', () => console.log(JSON.parse(data)));
});
// POST запит
const postData = JSON.stringify({ name: 'John' });
const options = {
hostname: 'api.example.com',
port: 80,
path: '/users',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData)
}
};
const req = http.request(options, (res) => {
let data = '';
res.on('data', (chunk) => data += chunk);
res.on('end', () => console.log(JSON.parse(data)));
});
req.write(postData);
req.end();http vs https vs http2
| Модуль | Протокол | Сценарій використання |
|---|---|---|
http | HTTP/1.1 | Розробка, внутрішні сервіси |
https | HTTPS (TLS) | Продакшн, публічні API |
http2 | HTTP/2 | Продуктивність (мультиплексування, серверний пуш) |
js
const https = require('https');
const fs = require('fs');
const server = https.createServer({
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
}, (req, res) => {
res.writeHead(200);
res.end('Безпечно!');
});Чому варто використовувати Express замість цього?
| Функція | Сировинний http | Express.js |
|---|---|---|
| Маршрутизація | Ручна if/else | app.get('/path') |
| Парсинг тіла | Ручне оброблення потоку | Вбудоване middleware |
| Middleware | Немає вбудованої підтримки | Підтримка першого класу |
| Статичні файли | Ручне | express.static() |
Порада: Розуміння сировинного модуля
httpдопомагає зрозуміти, що робить Express під капотом. У продакшні використовуйте Express або Fastify для підвищення продуктивності розробника, але знайте основи.
Коротка відповідь
Для співбесідиPremium
Коротка відповідь допоможе вам впевнено відповідати на цю тему під час співбесіди.