Brauzer və ya fetch http://localhost:3000/api/notes ünvanına müraciət edəndə 3000 portunu dinləyən, sorğunu oxuyan və cavab yazan bir proqram olmalıdır. «Node.js əsasları» dərsində hər şeyə eyni cavab verən beş sətirlik server gördük. Bu dərsdə yalnız daxili node:http modulu ilə əsl server quracağıq: metod və URL üzrə marşrutlar, JSON gövdəsinin oxunması, düzgün status kodları və başlıqlar, təhlükəsiz statik fayllar və kiçik qeydlər API-si. Sonda Express kimi freymvorkların niyə yarandığını görəcəksiniz.
createServer: sorğu və cavab
http.createServer(handler) server yaradır; handler hər sorğu üçün işləyir və iki obyekt alır. req oxunan axındır: req.method, req.url (sorğu sətri ilə birlikdə yol, məsələn /hello?name=Aysel) və req.headers (başlıq adları kiçik hərflə). res yazılan axındır: res.statusCode və res.setHeader() cavabın başını hazırlayır, res.write() gövdənin bir hissəsini göndərir, res.end() isə cavabı bitirir. server.listen(3000) 3000 portunu dinləməyə başlayır.
// 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');
});Gözlənilən nəticə
Listening on http://localhost:3000 GET /hello?name=Aysel node
// 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());Gözlənilən nəticə
200 OK true text/plain; charset=utf-8 node-http Salam! You asked for /hello?name=Aysel
fetch User-Agent kimi node göndərir. Başlıq adları böyük-kiçik hərfə həssas deyil: res.headers.get('x-lesson') X-Lesson-ı tapır.Davamını oxumaq üçün pulsuz qeydiyyatdan keç
Dərsin qalan bölmələri, test və qeydlər Educora hesabı ilə açılır. Qeydiyyat bir dəqiqə çəkir; irəliləyişin bütün cihazlarında saxlanılır.
Marşrutlaşdırma: metod + yol
Server adətən GET /api/time və POST /api/notes üçün fərqli işlər görür. URL sətir kimi gəlir, ona görə onu new URL(req.url, 'http://localhost') ilə ayırın: sorğu sətri olmadan pathname və ?name=Leyla üçün searchParams alırsınız. Sadə marşrutlaşdırıcı açarları 'METOD /yol' olan obyektdir. Yol var, amma metod uyğun deyilsə, düzgün cavab Allow başlığı ilə 405 Method Not Allowed-dır; yol ümumiyyətlə yoxdursa, 404 Not Found.
// 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'));// 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})` : ''}`);
}Gözlənilən nəticə
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') parametr olmayanda null qaytarır, ?? isə onu 'friend' ilə əvəz edir. /api/time üçün DELETE 405 aldı, çünki yol var, /api/weather isə 404, çünki yol yoxdur.| Kod | Nə vaxt | Qeyd |
|---|---|---|
| 200 OK | uğurlu oxuma və ya dəyişmə | |
| 201 Created | POST yeni resurs yaratdı | Location başlığı yeni ünvanı göstərir |
| 204 No Content | uğur, gövdə yoxdur (məsələn, DELETE) | |
| 400 Bad Request | səhv JSON və ya səhv məlumat | |
| 404 Not Found | belə yol və ya resurs yoxdur | |
| 405 Method Not Allowed | yol var, metod yox | Allow: GET kimi başlıq |
| 413 Payload Too Large | gövdə həddən böyükdür | |
| 415 Unsupported Media Type | Content-Type gözlənilən deyil | |
| 500 Internal Server Error | serverdə səhv (bug) | təfərrüatı müştəriyə göstərməyin |
JSON gövdəsini oxumaq
POST sorğusunun gövdəsi req.url-də deyil — o, req axınının özüdür və bir neçə hissə ilə gələ bilər. Ona görə hissələri for await ilə toplayın, Buffer.concat ilə birləşdirin (sətirləri deyil, Buffer-ləri birləşdirmək çoxbaytlı hərfləri qırmır) və yalnız sonra JSON.parse edin. Üç yoxlama serveri qoruyur: Content-Type JSON olmalıdır (415), gövdə həddi keçməməlidir — yoxsa hər kəs gigabaytlar göndərə bilər (413) — və qırıq JSON serveri dayandırmamalı, 400 verməlidir.
// 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 status kodunu daşıyır: emaledici sadəcə throw new HttpError(404, …) yazır, bir mərkəzi yer isə onu cavaba çevirir. Limit nümunə üçün 10 000 baytdır.Statik fayllar və path traversal
Saytlara fayllar da lazımdır: HTML, CSS, şəkillər. Sadəlövh yol qovluqla URL-i birləşdirməkdir. Lakin URL-də .. ola bilər. Brauzer və fetch /../ hissəsini ünvandan təmizləyir, hücumçu isə yox: curl --path-as-is onu toxunulmaz göndərir, %2f isə serverin özünün açdığı kodlaşdırılmış /-dir. Nəticə path traversal hücumudur: server açıq qovluqdan kənardakı faylları — konfiqurasiyanı, parolları, mənbə kodunu — oxuyur.
Təhlükəli
const file = path.join(ROOT, decodeURIComponent(req.url));
const info = await stat(file).catch(() => null);Təhlükəsiz
const file = resolveSafe(req.url.split('?')[0]);
const info = file && (await stat(file).catch(() => null));curl --path-as-is http://localhost:3000/../secret.txt və curl http://localhost:3000/..%2fsecret.txt hər ikisi public-dən kənardakı secret.txt-in məzmununu qaytardı. Sağ versiya əvvəl açır, birləşdirir, sonra nəticənin hələ də ROOT-un içində olduğunu yoxlayır.// 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 ilə yoxlama vacibdir: yalnız startsWith(ROOT) yazsanız, public-old qovluğu da «içəridə» sayılar. Fayl pipeline ilə axın kimi göndərilir və yaddaşa tam yüklənmir.$ 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-8Not found alır. Qırıq faiz kodlaşdırması (%E0%A4%A) decodeURIComponent-də xəta yaradır — o da tutulur. Content-Type fayl uzantısından gəlir, naməlum növlər application/octet-stream alır.Mini layihə: təmiz http üzərində qeydlər API-si
İndi hamısını birləşdirək: siyahı (GET /api/notes), yaratma (POST), bir qeydi oxuma (GET /api/notes/2) və silmə (DELETE). Qeydlər hələlik yaddaşdakı massivdədir — server yenidən başlayanda itir; verilənlər bazası «Express və verilənlər bazası» dərsində gələcək. Bütün xətalar handle funksiyasından atılır və bir .catch() onları JSON cavaba çevirir; gözlənilməz xətalar (status olmayan) loga yazılır, müştəri isə yalnız Internal error görür.
// 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] yol /api/notes/<rəqəmlər> deyilsə undefined verir, Number(undefined) isə NaN — yanlış qiymət, ona görə 404. res.writeHead(204).end() gövdəsiz cavab göndərir.// 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');Gözlənilən nəticə
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"}text yoxdur, 204 silindi, eyni qeydi ikinci dəfə silmək — 404, PUT — 405.İndi əl ilə nə yazdığımıza baxın: URL-in ayrılması, yolların müntəzəm ifadələrlə tutulması, gövdənin toplanması, növ və ölçü yoxlaması, xətaların statuslara çevrilməsi, təhlükəsiz statik fayllar. Hər layihəyə eyni kod lazımdır və hər əl ilə yazılmış surətin öz səhvi ola bilər. Freymvorklar bu hissələri yoxlanılmış hazır bloklara çevirir:
| Əl ilə (node:http) | Express |
|---|---|
new URL(req.url, …) + if / regex | app.get('/api/notes/:id', …), req.params.id |
readJson(req) | app.use(express.json()), req.body |
resolveSafe + pipeline | app.use(express.static('public')) |
HttpError + .catch() | xəta emal edən middleware |
res.writeHead(201, …).end(JSON.stringify(x)) | res.status(201).json(x) |
Tapşırıq
Marşrutlaşdırıcının qəlbini yazın: matchRoute(pattern, pathname) /api/notes/:id kimi şablonu yolla müqayisə etsin. Uyğun gəlirsə, parametrlər obyektini ({ id: '7' }, dəyərlər decodeURIComponent ilə açılmış), uyğun gəlmirsə null qaytarsın. Hissələrin sayı fərqlidirsə — null.
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'));Gözlənilən nəticə
{ id: '7' }
{ userId: '3', noteId: '15' }
null
{}
{ name: 'Gəncə' }Tapşırıq
Path traversal-a qarşı müdafiəni node:path olmadan yazın: resolveInside(urlPath) yolu açsın (decodeURIComponent, qırıq kodlaşdırmada null), / və \ üzrə bölsün, . və boş hissələri atsın, .. ilə bir addım geri getsin. Kökdən yuxarı çıxmaq cəhdi null versin. Nəticə / ilə birləşmiş nisbi yol olsun, boş yol isə index.html.
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)}`);Gözlənilən nəticə
/ -> 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
Yadda saxla
http.createServer((req, res) => …):req— metod, URL, başlıqlar və gövdə axını;res— status, başlıqlar vəend()ilə bitən gövdə.- URL-i
new URL(req.url, 'http://localhost')ilə ayırın; marşrut = metod +pathname; yol var, metod yoxdursa — 405 vəAllow. - JSON gövdəsi:
Content-Typeyoxlaması (415), ölçü həddi (413),Buffer.concat+JSON.parsevə qırıq JSON üçün 400. - Statik fayllar: açın, birləşdirin, nəticənin
ROOT + path.sepilə başladığını yoxlayın — yoxsa path traversal faylları sızdırır. - Xətaları bir yerdə statuslara çevirin və 500-də təfərrüat göstərməyin; bu təkrarlanan işlər freymvorkların yaranma səbəbidir.