Bir tarayıcı ya da fetch http://localhost:3000/api/notes adresine istek gönderince 3000 numaralı portu dinleyen, isteği okuyan ve yanıt yazan bir program olmalıdır. «Node.js temelleri» dersinde her şeye aynı yanıtı veren beş satırlık bir sunucu gördük. Bu derste yalnızca yerleşik node:http modülüyle gerçek bir sunucu kuracağız: metoda ve URL'ye göre rotalar, JSON gövdesini okumak, doğru durum kodları ve başlıklar, güvenli statik dosyalar ve küçük bir not API'si. Sonunda Express gibi çatıların neden var olduğunu göreceksiniz.
createServer: istek ve yanıt
http.createServer(handler) bir sunucu oluşturur; handler her istek için çalışır ve iki nesne alır. req okunabilir bir akıştır: req.method, req.url (sorgu dizesiyle birlikte yol, örneğin /hello?name=Aysel) ve req.headers (başlık adları küçük harfle). res yazılabilir bir akıştır: res.statusCode ve res.setHeader() yanıtın başını hazırlar, res.write() gövdenin bir parçasını gönderir, res.end() ise yanıtı bitirir. server.listen(3000) 3000 numaralı portu dinlemeye başlar.
// 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');
});Beklenen çıktı
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());Beklenen çıktı
200 OK true text/plain; charset=utf-8 node-http Salam! You asked for /hello?name=Aysel
fetch, User-Agent olarak node gönderir. Başlık adları büyük-küçük harfe duyarlı değildir: res.headers.get('x-lesson'), X-Lesson'ı bulur.Yönlendirme: metot + yol
Bir sunucu genellikle GET /api/time ve POST /api/notes için farklı işler yapar. URL bir metin olarak gelir, bu yüzden onu new URL(req.url, 'http://localhost') ile ayrıştırın: sorgu dizesi olmadan pathname ve ?name=Leyla için searchParams elde edersiniz. Basit bir yönlendirici, anahtarları 'METOT /yol' olan bir nesnedir. Yol var ama metot uymuyorsa doğru yanıt Allow başlığıyla 405 Method Not Allowed'dır; yol hiç yoksa 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})` : ''}`);
}Beklenen çıktı
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') parametre yoksa null döndürür, ?? de onu 'friend' ile değiştirir. /api/time için DELETE 405 aldı çünkü yol var; /api/weather ise 404 aldı çünkü yol yok.| Kod | Ne zaman | Not |
|---|---|---|
| 200 OK | başarılı okuma ya da değişiklik | |
| 201 Created | POST yeni bir kaynak oluşturdu | Location başlığı yeni adresi verir |
| 204 No Content | gövdesiz başarı (örneğin DELETE) | |
| 400 Bad Request | bozuk JSON ya da geçersiz veri | |
| 404 Not Found | böyle bir yol ya da kaynak yok | |
| 405 Method Not Allowed | yol var, metot yok | Allow: GET gibi bir başlık |
| 413 Payload Too Large | gövde sınırı aşıyor | |
| 415 Unsupported Media Type | Content-Type beklenen değil | |
| 500 Internal Server Error | sunucuda bir hata (bug) | ayrıntıları istemciye göstermeyin |
JSON gövdesini okumak
Bir POST isteğinin gövdesi req.url içinde değildir — req akışının kendisidir ve birkaç parça hâlinde gelebilir. Bu yüzden parçaları for await ile toplayın, Buffer.concat ile birleştirin (metinleri değil Buffer'ları birleştirmek çok baytlı harfleri bozmaz) ve ancak sonra JSON.parse çağırın. Üç kontrol sunucuyu korur: Content-Type JSON olmalı (415), gövde bir sınırı aşmamalı — yoksa herkes gigabaytlar gönderebilir (413) — ve bozuk JSON sunucuyu çökertmek yerine 400 vermeli.
// 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 bir durum kodu taşır: işleyici sadece throw new HttpError(404, …) yazar, merkezî tek bir yer de bunu yanıta çevirir. Sınır örnek için 10 000 bayttır.Statik dosyalar ve path traversal
Sitelerin dosyalara da ihtiyacı vardır: HTML, CSS, resimler. Saf yöntem klasörü ve URL'yi birleştirmektir. Ama bir URL .. içerebilir. Tarayıcı ve fetch adresten /../ kısmını temizler, saldırgan temizlemez: curl --path-as-is onu dokunmadan gönderir, %2f ise sunucunun kendisinin çözdüğü kodlanmış bir / işaretidir. Sonuç bir path traversal saldırısıdır: sunucu açık klasörün dışındaki dosyaları — yapılandırmayı, parolaları, kaynak kodunu — okur.
Tehlikeli
const file = path.join(ROOT, decodeURIComponent(req.url));
const info = await stat(file).catch(() => null);Güvenli
const file = resolveSafe(req.url.split('?')[0]);
const info = file && (await stat(file).catch(() => null));curl --path-as-is http://localhost:3000/../secret.txt ve curl http://localhost:3000/..%2fsecret.txt ikisi de public dışındaki secret.txt dosyasının içeriğini döndürdü. Sağdaki sürüm önce çözer, birleştirir, sonra sonucun hâlâ ROOT içinde olup olmadığına bakar.// 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 ile kontrol önemlidir: yalnızca startsWith(ROOT) yazarsanız public-old adlı bir klasör de «içeride» sayılır. Dosya pipeline ile akış olarak gönderilir ve belleğe bütünüyle yüklenmez.$ 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ıyor. Bozuk yüzde kodlaması (%E0%A4%A) decodeURIComponent'in hata fırlatmasına yol açar — o da yakalanır. Content-Type dosya uzantısından gelir; bilinmeyen türler application/octet-stream alır.Mini proje: saf http üzerinde not API'si
Şimdi hepsini birleştirelim: liste (GET /api/notes), oluşturma (POST), tek bir notu okuma (GET /api/notes/2) ve silme (DELETE). Notlar şimdilik bellekteki bir dizide duruyor — sunucu yeniden başlayınca kaybolur; veritabanı «Express ve veritabanı» dersinde gelecek. Tüm hatalar handle fonksiyonundan fırlatılır ve tek bir .catch() onları JSON yanıtlarına çevirir; beklenmeyen hatalar (durumu olmayanlar) loga yazılır, istemci ise yalnızca 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/<rakamlar> değilse undefined verir; Number(undefined) ise NaN'dır — yanlış bir değer, bu yüzden 404. res.writeHead(204).end() gövdesiz bir yanıt gönderir.// 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');Beklenen çıktı
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 yok, 204 silindi, aynı notu ikinci kez silmek — 404, PUT — 405.Şimdi elle neler yazdığımıza bakın: URL'yi ayrıştırmak, yolları düzenli ifadelerle eşlemek, gövdeyi toplamak, türü ve boyutu kontrol etmek, hataları durum kodlarına çevirmek, güvenli statik dosyalar. Her projenin aynı koda ihtiyacı vardır ve elle yazılmış her kopyanın kendi hatası olabilir. Çatılar bu parçaları denenmiş hazır bloklara dönüştürür:
| Elle (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() | hata işleyen middleware |
res.writeHead(201, …).end(JSON.stringify(x)) | res.status(201).json(x) |
Alıştırma
Bir yönlendiricinin kalbini yazın: matchRoute(pattern, pathname), /api/notes/:id gibi bir şablonu bir yolla karşılaştırsın. Eşleşirse parametre nesnesini ({ id: '7' }, değerler decodeURIComponent ile çözülmüş), eşleşmezse null döndürsün. Parça sayısı farklıysa 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'));Beklenen çıktı
{ id: '7' }
{ userId: '3', noteId: '15' }
null
{}
{ name: 'Gəncə' }Alıştırma
Path traversal savunmasını node:path olmadan yazın: resolveInside(urlPath) yolu çözsün (decodeURIComponent; bozuk kodlamada null), / ve \ işaretlerine göre bölsün, . ve boş parçaları atsın, .. görünce bir adım geri gitsin. Kökün üstüne çıkma girişimi null versin. Sonuç / ile birleştirilmiş göreli yol olsun, boş yol ise 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)}`);Beklenen çıktı
/ -> 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
Unutma
http.createServer((req, res) => …):reqmetot, URL, başlıklar ve gövde akışını verir;resdurum, başlıklar veend()ile biten gövdeyi alır.- URL'yi
new URL(req.url, 'http://localhost')ile ayrıştırın; rota = metot +pathname; yol var ama metot yoksa 405 veAllow. - JSON gövdesi:
Content-Typekontrolü (415), boyut sınırı (413),Buffer.concat+JSON.parseve bozuk JSON için 400. - Statik dosyalar: çözün, birleştirin, sonucun
ROOT + path.sepile başladığını kontrol edin — yoksa path traversal dosyaları sızdırır. - Hataları tek bir yerde durum kodlarına çevirin ve 500'de ayrıntı göstermeyin; bu tekrarlanan işler çatıların var olma nedenidir.