Node.js: веб-сервер на модуле http

Сервер только на встроенном `node:http`: `createServer`, объекты запроса и ответа, маршрутизация по методу и URL, чтение JSON-тела из потока, коды статуса и заголовки, безопасная раздача статических файлов (path traversal) и зачем нужны фреймворки.

  • Продвинутый
  • 25 мин
  • 12 вопросов
  • Урок 36 из 39

В этом уроке ты узнаешь

  • Создавать сервер через http.createServer, работать с объектами req и res и проверять его через fetch
  • Маршрутизировать запросы по методу и пути и возвращать правильный код статуса (200, 201, 204, 400, 404, 405, 413, 415)
  • Читать JSON-тело из потока с ограничением размера и защищать статические файлы от path traversal

Когда браузер или fetch обращается к http://localhost:3000/api/notes, какая-то программа должна слушать порт 3000, прочитать запрос и записать ответ. В уроке «Основы Node.js» мы видели сервер из пяти строк, который на всё отвечает одинаково. В этом уроке построим настоящий только на встроенном модуле node:http: маршруты по методу и URL, чтение JSON-тела, правильные коды статуса и заголовки, безопасные статические файлы и маленький API заметок. В конце станет ясно, зачем нужны фреймворки вроде Express.

createServer: запрос и ответ

http.createServer(handler) создаёт сервер; handler выполняется для каждого запроса и получает два объекта. req — поток чтения с req.method, req.url (путь вместе со строкой запроса, например /hello?name=Aysel) и req.headers (имена заголовков в нижнем регистре). res — поток записи: res.statusCode и res.setHeader() готовят начало ответа, res.write() отправляет часть тела, а res.end() завершает ответ. server.listen(3000) начинает слушать порт 3000.

JavaScript
// hello-server.mjs
import http from 'node:http';

const server = http.createServer((req, res) => {
  console.log(req.method, req.url, req.headers['user-agent']);

  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain; charset=utf-8');
  res.setHeader('X-Lesson', 'node-http');
  res.end(`Salam! You asked for ${req.url}\n`);
});

server.listen(3000, () => {
  console.log('Listening on http://localhost:3000');
});

Ожидаемый результат

Listening on http://localhost:3000
GET /hello?name=Aysel node
Сервер печатает строку на каждый запрос и работает, пока не нажать Ctrl+C.
JavaScript
// hello-client.mjs
const res = await fetch('http://localhost:3000/hello?name=Aysel');

console.log(res.status, res.statusText, res.ok);
console.log(res.headers.get('content-type'));
console.log(res.headers.get('x-lesson'));
console.log(await res.text());

Ожидаемый результат

200 OK true
text/plain; charset=utf-8
node-http
Salam! You asked for /hello?name=Aysel
Запустите во втором терминале, пока сервер работает. fetch в Node.js отправляет node в качестве User-Agent. Имена заголовков не зависят от регистра: res.headers.get('x-lesson') находит X-Lesson.

Чтобы читать дальше, зарегистрируйся бесплатно

Остальные разделы урока, тест и заметки открываются с аккаунтом Educora. Регистрация занимает минуту, а прогресс сохраняется на всех твоих устройствах.

Маршрутизация: метод + путь

Обычно сервер делает разное для GET /api/time и POST /api/notes. URL приходит строкой, поэтому разберите его через new URL(req.url, 'http://localhost'): получите pathname без строки запроса и searchParams для ?name=Leyla. Простой маршрутизатор — объект с ключами вида 'МЕТОД /путь'. Если путь есть, но метод не подходит, правильный ответ — 405 Method Not Allowed с заголовком Allow; если пути нет вовсе — 404 Not Found.

JavaScript
// router-server.mjs
import http from 'node:http';

function send(res, status, data) {
  res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
  res.end(JSON.stringify(data));
}

const routes = {
  'GET /api/greet': (req, res, url) =>
    send(res, 200, { text: `Salam, ${url.searchParams.get('name') ?? 'friend'}!` }),
  'GET /api/time': (req, res) => send(res, 200, { city: 'Baku', utcOffset: '+04:00' }),
};

const server = http.createServer((req, res) => {
  const url = new URL(req.url, `http://${req.headers.host}`);
  const handler = routes[`${req.method} ${url.pathname}`];
  if (handler) return handler(req, res, url);

  const allowed = Object.keys(routes)
    .filter((key) => key.endsWith(` ${url.pathname}`))
    .map((key) => key.split(' ')[0]);
  if (allowed.length) {
    res.setHeader('Allow', allowed.join(', '));
    return send(res, 405, { error: `${req.method} is not allowed here` });
  }
  send(res, 404, { error: `Nothing at ${url.pathname}` });
});

server.listen(3000, () => console.log('Listening on http://localhost:3000'));
JavaScript
// router-client.mjs
const base = 'http://localhost:3000';
const requests = [
  ['GET', '/api/greet?name=Leyla'],
  ['GET', '/api/greet'],
  ['GET', '/api/time'],
  ['DELETE', '/api/time'],
  ['GET', '/api/weather'],
];

for (const [method, path] of requests) {
  const res = await fetch(base + path, { method });
  const allow = res.headers.get('allow');
  const body = await res.text();
  console.log(`${method} ${path} → ${res.status} ${body}${allow ? ` (Allow: ${allow})` : ''}`);
}

Ожидаемый результат

GET /api/greet?name=Leyla → 200 {"text":"Salam, Leyla!"}
GET /api/greet → 200 {"text":"Salam, friend!"}
GET /api/time → 200 {"city":"Baku","utcOffset":"+04:00"}
DELETE /api/time → 405 {"error":"DELETE is not allowed here"} (Allow: GET)
GET /api/weather → 404 {"error":"Nothing at /api/weather"}
url.searchParams.get('name') возвращает null, если параметра нет, и ?? заменяет его на 'friend'. DELETE для /api/time получил 405, потому что путь есть, а /api/weather — 404, потому что его нет.
КодКогдаЗаметка
200 OKуспешное чтение или изменение
201 CreatedPOST создал новый ресурсзаголовок Location даёт новый адрес
204 No Contentуспех без тела (например, DELETE)
400 Bad Requestсломанный JSON или неверные данные
404 Not Foundнет такого пути или ресурса
405 Method Not Allowedпуть есть, метода нетзаголовок вроде Allow: GET
413 Payload Too Largeтело больше лимита
415 Unsupported Media TypeContent-Type не тот, что ожидался
500 Internal Server Errorошибка (баг) на серверене показывайте клиенту подробности

Чтение JSON-тела

Тело POST-запроса находится не в req.url — это сам поток req, и оно может прийти несколькими кусками. Поэтому собирайте куски через for await, соединяйте через Buffer.concat (склеивание буферов, а не строк, не ломает многобайтовые буквы) и только потом вызывайте JSON.parse. Сервер защищают три проверки: Content-Type должен быть JSON (415), тело не должно превышать лимит — иначе кто угодно пришлёт гигабайты (413), — а сломанный JSON должен давать 400, а не ронять сервер.

JavaScript
// http-utils.mjs
export class HttpError extends Error {
  constructor(status, message) {
    super(message);
    this.status = status;
  }
}

export function send(res, status, data) {
  res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
  res.end(JSON.stringify(data));
}

export async function readJson(req, limit = 10_000) {
  if (!req.headers['content-type']?.startsWith('application/json')) {
    throw new HttpError(415, 'Expected Content-Type: application/json');
  }
  const chunks = [];
  let size = 0;
  for await (const chunk of req) {
    size += chunk.length;
    if (size > limit) throw new HttpError(413, `Body is larger than ${limit} bytes`);
    chunks.push(chunk);
  }
  try {
    return JSON.parse(Buffer.concat(chunks).toString('utf8'));
  } catch {
    throw new HttpError(400, 'Body is not valid JSON');
  }
}
HttpError несёт код статуса: обработчик просто пишет throw new HttpError(404, …), а одно центральное место превращает это в ответ. Лимит для примера — 10 000 байт.

Статические файлы и path traversal

Сайтам нужны и файлы: HTML, CSS, картинки. Наивный способ — склеить папку и URL. Но в URL может оказаться ... Браузер и fetch убирают /../ из адреса, а атакующий — нет: curl --path-as-is отправляет его нетронутым, а %2f — это закодированный /, который сервер раскодирует сам. Результат — атака path traversal: сервер читает файлы вне публичной папки — конфигурацию, пароли, исходный код.

Опасно

const file = path.join(ROOT, decodeURIComponent(req.url));
const info = await stat(file).catch(() => null);

Безопасно

const file = resolveSafe(req.url.split('?')[0]);
const info = file && (await stat(file).catch(() => null));
Левая версия проверена: curl --path-as-is http://localhost:3000/../secret.txt и curl http://localhost:3000/..%2fsecret.txt вернули содержимое secret.txt, лежащего вне public. Правая версия раскодирует, склеивает и затем проверяет, что результат всё ещё внутри ROOT.
JavaScript
// static-server.mjs
import http from 'node:http';
import { createReadStream } from 'node:fs';
import { stat } from 'node:fs/promises';
import { pipeline } from 'node:stream/promises';
import path from 'node:path';

const ROOT = path.join(import.meta.dirname, 'public');
const TYPES = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'text/javascript' };

function resolveSafe(urlPath) {
  let decoded;
  try {
    decoded = decodeURIComponent(urlPath);
  } catch {
    return null;
  }
  const file = path.join(ROOT, decoded === '/' ? 'index.html' : decoded);
  return file.startsWith(ROOT + path.sep) ? file : null;
}

http.createServer(async (req, res) => {
  const file = resolveSafe(req.url.split('?')[0]);
  const info = file && (await stat(file).catch(() => null));
  if (!info?.isFile()) return res.writeHead(404, { 'Content-Type': 'text/plain' }).end('Not found\n');

  const type = TYPES[path.extname(file)] ?? 'application/octet-stream';
  res.writeHead(200, { 'Content-Type': type, 'Content-Length': info.size });
  await pipeline(createReadStream(file), res).catch((error) => console.error('send failed:', error.code));
}).listen(3000, () => console.log('Static files on http://localhost:3000'));
Важно проверять именно ROOT + path.sep: с одним startsWith(ROOT) папка public-old тоже считалась бы «внутри». Файл отправляется потоком через pipeline и целиком в память не загружается.
Terminal
$ curl http://localhost:3000/
<h1>Salam!</h1>
$ curl http://localhost:3000/css/site.css
h1 { color: teal; }
$ curl --path-as-is http://localhost:3000/../secret.txt
Not found
$ curl http://localhost:3000/..%2fsecret.txt
Not found
$ curl http://localhost:3000/%E0%A4%A
Not found
$ curl -o /dev/null -w "%{http_code} %{content_type}\n" http://localhost:3000/index.html
200 text/html; charset=utf-8
Те же атаки теперь получают Not found. Сломанное процентное кодирование (%E0%A4%A) заставляет decodeURIComponent выбросить ошибку — она тоже перехвачена. Content-Type берётся из расширения файла, неизвестные типы получают application/octet-stream.

Мини-проект: API заметок на чистом http

Теперь соберём всё вместе: список (GET /api/notes), создание (POST), чтение одной заметки (GET /api/notes/2) и удаление (DELETE). Заметки пока живут в массиве в памяти — при перезапуске сервера они пропадают; база данных появится в уроке «Express и база данных». Все ошибки выбрасываются из функции handle, и один .catch() превращает их в JSON-ответы; неожиданные ошибки (без статуса) пишутся в лог, а клиент видит только Internal error.

JavaScript
// notes-server.mjs
import http from 'node:http';
import { HttpError, send, readJson } from './http-utils.mjs';

const notes = [{ id: 1, text: 'Buy bread' }];
let nextId = 2;

async function handle(req, res) {
  const { pathname } = new URL(req.url, 'http://localhost');
  if (pathname === '/api/notes' && req.method === 'GET') return send(res, 200, notes);
  if (pathname === '/api/notes' && req.method === 'POST') {
    const { text } = await readJson(req);
    if (typeof text !== 'string' || !text.trim()) throw new HttpError(400, 'text is required');
    const note = { id: nextId++, text: text.trim() };
    notes.push(note);
    res.setHeader('Location', `/api/notes/${note.id}`);
    return send(res, 201, note);
  }
  const id = Number(pathname.match(/^\/api\/notes\/(\d+)$/)?.[1]);
  if (!id) throw new HttpError(404, `Nothing at ${pathname}`);
  const index = notes.findIndex((n) => n.id === id);
  if (index === -1) throw new HttpError(404, 'Note not found');
  if (req.method === 'GET') return send(res, 200, notes[index]);
  if (req.method !== 'DELETE') throw new HttpError(405, 'Method not allowed');
  notes.splice(index, 1);
  res.writeHead(204).end();
}

http.createServer((req, res) => handle(req, res).catch((error) => {
  if (!error.status) console.error(error);
  send(res, error.status ?? 500, { error: error.status ? error.message : 'Internal error' });
})).listen(3000, () => console.log('Notes API on http://localhost:3000'));
pathname.match(...)?.[1] даёт undefined, если путь не /api/notes/<цифры>, а Number(undefined) — это NaN, ложное значение, отсюда 404. res.writeHead(204).end() отправляет ответ без тела.
JavaScript
// notes-client.mjs
const base = 'http://localhost:3000/api/notes';

async function call(method, url, body, type = 'application/json') {
  const headers = body === undefined ? {} : { 'Content-Type': type };
  const res = await fetch(url, { method, headers, body });
  const text = await res.text();
  console.log(`${method} ${url.slice(21)} → ${res.status}${text ? ` ${text}` : ''}`);
}

await call('POST', base, JSON.stringify({ text: 'Call Leyla' }));
await call('POST', base, '{"text": "oops"');
await call('POST', base, 'text=hi', 'text/plain');
await call('POST', base, JSON.stringify({ text: 'x'.repeat(20_000) }));
await call('POST', base, JSON.stringify({ title: 'no text' }));
await call('GET', `${base}/2`);
await call('DELETE', `${base}/1`);
await call('DELETE', `${base}/1`);
await call('PUT', `${base}/2`);
await call('GET', base);
await call('GET', 'http://localhost:3000/api/users');

Ожидаемый результат

POST /api/notes → 201 {"id":2,"text":"Call Leyla"}
POST /api/notes → 400 {"error":"Body is not valid JSON"}
POST /api/notes → 415 {"error":"Expected Content-Type: application/json"}
POST /api/notes → 413 {"error":"Body is larger than 10000 bytes"}
POST /api/notes → 400 {"error":"text is required"}
GET /api/notes/2 → 200 {"id":2,"text":"Call Leyla"}
DELETE /api/notes/1 → 204
DELETE /api/notes/1 → 404 {"error":"Note not found"}
PUT /api/notes/2 → 405 {"error":"Method not allowed"}
GET /api/notes → 200 [{"id":2,"text":"Call Leyla"}]
GET /api/users → 404 {"error":"Nothing at /api/users"}
Каждая строка — один запрос: 201 создано, 400 сломанный JSON, 415 не тот тип, 413 большое тело (20 000 байт > 10 000), 400 нет text, 204 удалено, повторное удаление той же заметки — 404, PUT — 405.

Теперь посмотрите, что мы написали вручную: разбор URL, сопоставление путей регулярными выражениями, сбор тела, проверку типа и размера, превращение ошибок в статусы, безопасные статические файлы. Каждому проекту нужен тот же код, и в каждой самодельной копии может быть своя ошибка. Фреймворки превращают эти части в проверенные готовые блоки:

Вручную (node:http)Express
new URL(req.url, …) + if / regexapp.get('/api/notes/:id', …), req.params.id
readJson(req)app.use(express.json()), req.body
resolveSafe + pipelineapp.use(express.static('public'))
HttpError + .catch()middleware обработки ошибок
res.writeHead(201, …).end(JSON.stringify(x))res.status(201).json(x)

Задание

Напишите сердце маршрутизатора: matchRoute(pattern, pathname) сравнивает шаблон вроде /api/notes/:id с путём. При совпадении возвращает объект параметров ({ id: '7' }, значения раскодированы через decodeURIComponent), иначе null. Разное число сегментов — null.

Задание · JavaScript
function matchRoute(pattern, pathname) {
  const want = pattern.split('/').filter(Boolean);
  const got = pathname.split('/').filter(Boolean);
  // compare segment by segment; ':name' segments go into params
}

console.log(matchRoute('/api/notes/:id', '/api/notes/7'));
console.log(matchRoute('/api/users/:userId/notes/:noteId', '/api/users/3/notes/15'));
console.log(matchRoute('/api/notes/:id', '/api/notes'));
console.log(matchRoute('/api/notes', '/api/notes/'));
console.log(matchRoute('/api/tags/:name', '/api/tags/G%C9%99nc%C9%99'));
Ожидаемый результат
{ id: '7' }
{ userId: '3', noteId: '15' }
null
{}
{ name: 'Gəncə' }

Задание

Напишите защиту от path traversal без node:path: resolveInside(urlPath) раскодирует путь (decodeURIComponent; при сломанной кодировке — null), делит его по / и \, отбрасывает . и пустые части, а на .. делает шаг назад. Попытка подняться выше корня даёт null. Результат — относительный путь, склеенный через /, а пустой путь превращается в index.html.

Задание · JavaScript
function resolveInside(urlPath) {
  // 1) decode (try/catch → null)
  // 2) split on / and \, walk the parts with a stack
  // 3) '..' on an empty stack → null
}

const tests = ['/', '/css/./site.css', '/img/../css/site.css', '/../secret.txt',
  '/css/..%2f..%2fsecret.txt', '/..%5csecret.txt', '/%E0%A4%A', '/docs/My%20CV.pdf'];
for (const t of tests) console.log(`${t} -> ${resolveInside(t)}`);
Ожидаемый результат
/ -> index.html
/css/./site.css -> css/site.css
/img/../css/site.css -> css/site.css
/../secret.txt -> null
/css/..%2f..%2fsecret.txt -> null
/..%5csecret.txt -> null
/%E0%A4%A -> null
/docs/My%20CV.pdf -> docs/My CV.pdf

Запомни

  • http.createServer((req, res) => …): req — метод, URL, заголовки и поток тела; res — статус, заголовки и тело, завершаемое end().
  • Разбирайте URL через new URL(req.url, 'http://localhost'); маршрут = метод + pathname; путь есть, метода нет — 405 и Allow.
  • JSON-тело: проверка Content-Type (415), лимит размера (413), Buffer.concat + JSON.parse и 400 для сломанного JSON.
  • Статические файлы: раскодировать, склеить, проверить, что результат начинается с ROOT + path.sep, — иначе path traversal сольёт файлы.
  • Превращайте ошибки в статусы в одном месте и не показывайте подробностей при 500; эта повторяющаяся работа — причина появления фреймворков.
Заметил ошибку или неточность в уроке?

Проверь себя

Вопросов: 12. Каждый правильный ответ приносит XP.

Вопрос 1 / 12

Вопрос 1 / 12. Клиент отправил GET /search?q=tea. Чему равно req.url?