HTTP من جُوّه: الـ methods والـ status codes والـ headers
HTTP كلام مكتوب: سطر الـ request، والـ headers، وسطر فاضي، والـ body، وبنشوفه خام على socket. الـ methods ومعناها (safe و idempotent)، وأكواد الـ status بمجموعاتها والفرق بين 400 و 401 و 403 و 404 و 409 و 415 و 422. وأهم الـ headers: Content-Type و Location و Allow و ETag و Cache-Control، و conditional GET بـ 304.
نص شرح المعلم والكود الذي كتبه ونتيجة تشغيله، بنفس ترتيب الدرس.
أهلًا بيك في قسم HTTP و Express. قبل أي framework، لازم تفهم HTTP نفسه، لأن كل حاجة فوقه مبنية عليه. والمفاجأة: HTTP one point one مجرد كلام مكتوب بين جهازين. هنعمل server بـ node colon http، وهنكلمه من غير متصفح، بـ socket خام، ونكتب الـ request بإيدينا: سطر أول: الـ method والـ path والإصدار. وبعده headers. وبعده سطر فاضي، ومعناه: خلصت. نشغّل.
import http from "node:http";
import net from "node:net";
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "text/plain; charset=utf-8");
res.end("أهلًا");
});
server.listen(3000, () => {
// client بإيدينا: بنكتب الـ request كنص على socket
const socket = net.connect(3000, "localhost", () => {
socket.write("GET /hello HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n");
});
let raw = "";
socket.on("data", (d) => (raw += d));
socket.on("end", () => {
console.log(raw.replace(/^Date: .*\r\n/m, ""));
server.close();
});
});المخرجات
$ node server.js HTTP/1.1 200 OK Content-Type: text/plain; charset=utf-8 Connection: close Content-Length: 10 أهلًا
ده الـ response الخام، زي ما بيمشي على الشبكة. أول سطر: status line: الإصدار، و two hundred، و OK. بعده headers: Content-Type اللي إحنا حطيناه، و Content-Length بعدد الـ bytes، وخد بالك إنها عشرة مش خمسة، لأن الحروف عربي. وبعدين سطر فاضي. وبعدين الـ body. كل framework، Express أو غيره، في الآخر بيكتب الكلام ده.
الـ methods. كل method ليها معنى، والـ clients والـ caches والـ proxies بيعتمدوا على المعنى ده. GET: هات، وما بتغيّرش حاجة، واسمها safe. POST: اعمل حاجة جديدة. PUT: استبدل الحاجة كلها. PATCH: عدّل جزء. DELETE: امسح. وفيه كلمة مهمة: idempotent، يعني لو بعتّه مرة أو عشرة، النتيجة واحدة. GET و PUT و DELETE كده، و POST لا: كل مرة بيعمل حاجة جديدة. وده بيفرق جامد في الـ retry: الـ client يقدر يعيد الـ idempotent بأمان. server صغير لـ items، بـ node colon http من غير مكتبات، علشان نشوف كل قرار بعينينا. send بتكتب الـ status والـ headers والـ JSON. readJson بتقرا الـ body chunks، لأن الـ request نفسه stream. GET للكل ولواحد. POST بيتأكد إن الـ Content-Type JSON، وإلا four fifteen. ولو name ناقص four hundred. ولو تمام two oh one، ومعاه header اسمه Location فيه مكان الحاجة الجديدة. DELETE بيرد two oh four، يعني تمام ومفيش body. وأي method تانية four oh five، ومعاه Allow.
نشغّل ونبعت requests، وهنطبع الـ headers كمان.
import http from "node:http";
const items = new Map([[1, { id: 1, name: "Node" }]]);
let nextId = 2;
function send(res, status, body, headers = {}) {
res.writeHead(status, { "Content-Type": "application/json", ...headers });
res.end(body === undefined ? undefined : JSON.stringify(body));
}
async function readJson(req) {
let raw = "";
for await (const chunk of req) raw += chunk;
return JSON.parse(raw);
}
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, "http://localhost");
const match = url.pathname.match(/^\/items(?:\/(\d+))?$/);
if (!match) return send(res, 404, { error: "مش موجود" });
const id = match[1] && Number(match[1]);
if (req.method === "GET" && !id) return send(res, 200, [...items.values()]);
if (req.method === "GET") {
const item = items.get(id);
return item ? send(res, 200, item) : send(res, 404, { error: "مش موجود" });
}
if (req.method === "POST" && !id) {
if (req.headers["content-type"] !== "application/json") {
return send(res, 415, { error: "ابعت JSON" });
}
const body = await readJson(req);
if (!body.name) return send(res, 400, { error: "name مطلوب" });
const item = { id: nextId++, name: body.name };
items.set(item.id, item);
return send(res, 201, item, { Location: `/items/${item.id}` });
}
if (req.method === "DELETE" && id) {
items.delete(id);
return send(res, 204);
}
send(res, 405, { error: "method مش مسموح" }, { Allow: id ? "GET, DELETE" : "GET, POST" });
});
server.listen(3000, () => console.log("http://localhost:3000"));المخرجات
$ node server.js
http://localhost:3000
→ GET /items
← 200 OK
[
{
"id": 1,
"name": "Node"
}
]
→ POST /items
{"name":"PostgreSQL"}
← 201 Created
connection: keep-alive
content-type: application/json
keep-alive: timeout=5
location: /items/2
transfer-encoding: chunked
{
"id": 2,
"name": "PostgreSQL"
}
→ POST /items
{}
← 400 Bad Request
{
"error": "name مطلوب"
}
→ POST /items
name=Redis
← 415 Unsupported Media Type
{
"error": "ابعت JSON"
}
→ GET /items/9
← 404 Not Found
{
"error": "مش موجود"
}
→ PUT /items
← 405 Method Not Allowed
allow: GET, POST
connection: keep-alive
content-type: application/json
keep-alive: timeout=5
transfer-encoding: chunked
{
"error": "method مش مسموح"
}
→ DELETE /items/2
← 204 No ContentGET رجّعت الـ list. POST رجّعت two oh one، و location slash items slash two. من غير name: four hundred. بـ text plain: four fifteen، Unsupported Media Type. item مش موجود: four oh four. PUT على الـ list: four oh five، و allow بيقول المسموح. و DELETE: two oh four. كل رقم هنا بيقول للـ client حاجة دقيقة، يقدر يتصرف على أساسها من غير ما يقرا الرسالة.
أكواد الـ status، أهم حاجة تحفَظها. two hundreds: نجح. three hundreds: روح حتة تانية، أو استخدم اللي عندك. four hundreds: غلطة الـ client. five hundreds: غلطة الـ server. والأكواد اللي الناس بتلخبط فيها: four oh one: مش عارفك، سجّل دخول. four oh three: عارفك، بس مش مسموحلك. four oh nine: conflict، زي إيميل متسجل قبل كده. four twenty two: الـ JSON سليم بس القيم غلط. four twenty nine: كتير، استنى. five oh three: مش متاح دلوقتي، جرّب بعدين. التحدي: conditional GET بـ ETag. الكورس عنده version، والـ ETag هو بصمة النسخة دي. الـ client بيبعت آخر ETag شافه في header اسمه If-None-Match. لو لسه هو هو: three oh four، يعني استخدم اللي عندك، ومن غير body، فبنوفر bandwidth. لو اتغيّر: two hundred بالجديد. و HEAD: نفس الـ headers من غير body. وأي method تانية four oh five. حالات الاختبار الخمسة في الكومنت.
server لـ /course: ETag = "v3"، If-None-Match مطابق ← 304، غير كده 200 بالـ JSON و Cache-Control: no-cache، و HEAD من غير body، وغيرهم 405 + Allow.
الحل. أي path غير slash course: four oh four. الـ etag من الـ version بالـ quotes. أي method غير GET و HEAD: four oh five ومعاها Allow. لو If-None-Match مطابق: three oh four بالـ ETag بس. وغير كده two hundred بالـ headers، والـ body بس لو مش HEAD. نشغّل بالخمس حالات.
import http from "node:http";
const course = { id: 1, title: "Node.js", version: 3 };
const server = http.createServer((req, res) => {
if (req.url !== "/course") {
res.writeHead(404);
return res.end();
}
const etag = `"v${course.version}"`;
if (req.method !== "GET" && req.method !== "HEAD") {
res.writeHead(405, { Allow: "GET, HEAD" });
return res.end();
}
if (req.headers["if-none-match"] === etag) {
res.writeHead(304, { ETag: etag });
return res.end();
}
res.writeHead(200, {
"Content-Type": "application/json",
ETag: etag,
"Cache-Control": "no-cache",
});
res.end(req.method === "HEAD" ? undefined : JSON.stringify(course));
});
server.listen(3000, () => console.log("http://localhost:3000"));المخرجات
$ node server.js
http://localhost:3000
→ GET /course
← 200 OK
cache-control: no-cache
connection: keep-alive
content-type: application/json
etag: "v3"
keep-alive: timeout=5
transfer-encoding: chunked
{
"id": 1,
"title": "Node.js",
"version": 3
}
→ GET /course
← 304 Not Modified
→ GET /course
← 200 OK
{
"id": 1,
"title": "Node.js",
"version": 3
}
→ HEAD /course
← 200 OK
→ DELETE /course
← 405 Method Not Allowed
allow: GET, HEAD
connection: keep-alive
keep-alive: timeout=5
transfer-encoding: chunkedtwo hundred بالـ etag و cache-control. بنفس الـ ETag: three oh four، Not Modified، ومفيش body. بـ ETag قديم: two hundred بالجديد. HEAD: two hundred من غير body. و DELETE: four oh five و allow. المتصفحات والـ CDNs بتعمل الحوار ده لوحدها لو الـ server بيبعت ETag، وده من أرخص طرق تسريع أي API. الدرس الجاي: Express، و الـ routing ومعاملات الـ paths.
03 / دروس المسار (122)
- 01أهلًا بيك: يعني إيه backend، والكورس ده ماشي إزاي
- 02الملفات والفولدرات والـ terminal: تتحرك على جهازك زي المبرمجين
- 03Node وأول برنامج: تشغّل وتقرا رسالة الخطأ
- 04القيم والمتغيرات والأنواع: const و let و typeof
- 05القرارات والتكرار: if و === والـ truthy والـ loops
- 06الـ functions: parameters و return والـ arrow functions والـ scope
- 07الـ objects والـ arrays: destructuring و spread و map و filter و reduce
- 08JSON والنصوص والتواريخ: اللغة اللي الـ backend بيتكلم بيها
- 09الـ callbacks والـ closures وأول لمسة async: setTimeout
- 10الـ classes والـ errors: throw و try/catch و stack trace
- 11git: تحفَظ كل خطوة وترجعلها، وما تسرّبش أسرارك
- 12ESM و CommonJS و package exports: Node بيلاقي الـ modules إزاي
- 13الـ Promises و async/await: sequential و parallel والأخطاء والإلغاء
- 14الـ event loop والـ microtasks: Node بيعمل كل حاجة بـ thread واحد إزاي
- 15الـ Streams والـ Backpressure: ملفات أكبر من الـ memory
- 16الـ File System والـ paths: قراية وكتابة صح، ومن غير path traversal
- 17الـ Buffers والبيانات الـ binary: الـ bytes من جُوّه
- 18Crypto APIs والأسرار: random و hash و HMAC و AES-GCM
- 19الـ Worker Threads: شغل CPU تقيل من غير ما توقف الـ server
- 20الـ Errors على مستوى الـ process: operational و programmer و crash-only
- 21الـ Node test runner والـ debugging: tests من غير مكتبات
- 22HTTP من جُوّه: الـ methods والـ status codes والـ headersانت هنا
- 23Express والـ Routing: الـ params والـ query والترتيب والـ Router
- 24Express 5: إيه اللي اتغيّر، وإزاي تنقل مشروع قديم
- 25الـ Middleware ودورة حياة الـ request جُوّه Express
- 26Validation للمدخلات بـ Zod: ما تصدّقش أي حاجة جاية من برة
- 27تصنيف الأخطاء و Problem Details: شكل واحد لكل الـ errors
- 28الـ CORS والـ Cookies: المتصفح بيحمي المستخدم إزاي
- 29رفع الملفات وحدود الحجم: multer من غير ثغرات
- 30الـ Realtime: Server-Sent Events و WebSockets
- 31OpenAPI والـ API Versioning: عقد مكتوب، وتغيير من غير ما تكسر حد
- 32PostgreSQL: الـ DDL وأنواع البيانات الصح لكل عمود
- 33الـ Constraints: PK و FK و UNIQUE و CHECK — الـ database بتحمي نفسها
- 34الـ Normalization والـ ERD: تقسّم البيانات صح من أول يوم
- 35الـ JOINs والتجميع: INNER و LEFT و GROUP BY و HAVING و window functions
- 36JSONB في PostgreSQL: إمتى تستخدمه، وإزاي تسأله وتعمله index
- 37الـ Indexes من جُوّه: B-tree و GIN و BRIN
- 38Partial و Covering indexes: indexes أصغر وأسرع
- 39الـ Pagination بالـ Keyset: ليه OFFSET بيبطّأ وبيكرر
- 40Full Text Search في Postgres: بحث بالكلمات، بالعربي والإنجليزي
- 41EXPLAIN ANALYZE والـ Planner: اقرا الـ plan وصلّح الـ query
- 42الـ Transactions بـ node-postgres: كله أو ولا حاجة
- 43الـ MVCC ومستويات الـ Isolation: transactions كتير في نفس الوقت
- 44الـ Locks والـ Deadlocks: مين مستني مين
- 45SKIP LOCKED و Job Leasing: Postgres كـ job queue
- 46Row Level Security والـ Multi-tenancy: كل عميل يشوف بياناته بس
- 47Migrations من غير downtime: expand و backfill و contract
- 48الـ Replication والـ Read Replicas: نسخ حية من الـ database
- 49الـ Connection Pooling و PgBouncer: connections أقل، requests أكتر
- 50الـ Partitioning والـ VACUUM والمراقبة: Postgres على المدى الطويل
- 51Redis وأنواع البيانات: strings و hashes و lists و sets و sorted sets
- 52Cache-aside والـ TTL: Redis قدام الـ database
- 53الـ Cache invalidation والـ Stampede: لما الـ key الشهير يموت
- 54Lua والـ Atomicity في Redis: كام أمر كأنهم أمر واحد
- 55الـ Rate Limiting في Redis: fixed window و sliding window و token bucket
- 56الـ Sessions في Redis: تسجيل دخول تقدر تلغيه في أي وقت
- 57Redis Streams والـ Consumer Groups: log بيتوزع على workers
- 58Pub/Sub و BullMQ: إشارات بين الـ instances، وطوابير شغل محترمة
- 59Redis لما يقع: الـ persistence (RDB و AOF) والـ replication
- 60Redis في الإنتاج: الـ ACLs والـ Cluster والمراقبة
- 61تخزين الـ Passwords بـ Argon2id: صح من أول مرة
- 62Session Fixation والـ Rotation: id جديد مع كل صلاحية جديدة
- 63الـ Cookie Flags والـ CSRF: المتصفح بيبعت الـ cookie، فلازم تتأكد مين اللي طلب
- 64الـ XSS والـ Content Security Policy: ما تخليش النص يتحوّل لـ code
- 65الـ OAuth و OpenID Connect و PKCE: login بـ Google من غير ما تشوف الـ password
- 66التأكد من الـ JWT صح: التوقيع والـ claims والـ scopes
- 67الـ BOLA و BFLA: الـ token السليم مش معناه إن الطلب مسموح
- 68الـ RBAC و ABAC والملكية: policy واحدة بدل ifs متفرقة
- 69الـ MFA والـ recovery: التاني factor اللي بجد
- 70الـ Passkeys و WebAuthn: login من غير password وضد الـ phishing
- 71الـ Threat Modeling بـ STRIDE: فكّر زي المهاجم قبل ما تكتب code
- 72الـ SQL Injection والـ Parameterization: الـ data ما تبقاش code
- 73الـ SSRF والـ Egress: ما تخليش الـ server بتاعك يزور الشبكة الداخلية
- 74الـ Security Headers والـ TLS: كل response يقول للـ browser يحمي المستخدم إزاي
- 75توقيع الـ Webhooks والـ Replay: الـ webhook ده جاي فعلًا من Stripe؟
- 76تغيير الأسرار والـ HMAC: إزاي تغيّر مفتاح من غير ما كل حاجة تقع
- 77سلسلة التوريد والـ SBOM: إنت واثق في ألف package ما تعرفهمش؟
- 78الـ Audit والـ Privacy Logs: سجّل مين عمل إيه، من غير ما تسجّل الأسرار
- 79اختبار الأمان و OWASP ASVS: الأمن جُوّه الـ CI، مش audit آخر السنة
- 80الـ Prototype Pollution والـ Resource DoS: request واحد يخلّي الكل admin أو يوقّع الـ server
- 81الـ SLI والـ SLO والـ Error Budget: إمتى تصحّي الـ on-call وإمتى تسيبه نايم
- 82الـ Event Loop Delay والـ ELU: لما Node نفسه يتخنق
- 83الـ Worker Threads والـ CPU Profiling: الشغل التقيل بره الـ event loop، والوقت راح فين
- 84الـ Memory والـ GC والـ Leaks: الـ process اللي بيكبر لحد ما يقع
- 85الـ N+1 Queries والـ DataLoader: صفحة واحدة بمِيّتين query
- 86الـ HTTP Caching والـ Compression: أسرع request هو اللي ما بيوصلش
- 87الـ Load Testing والـ Soak Testing: الـ server بيستحمل قد إيه بجد
- 88الـ Concurrency Limits والـ Bulkheads: dependency بطيئة ما توقعش الـ app كله
- 89الـ Timeouts والـ Retries والـ Circuit Breakers: إزاي تتعامل مع dependency بطيئة أو واقعة
- 90OpenTelemetry والـ Distributed Tracing: الـ request راح فين وضاع وقته فين
- 91Docker Layers والـ Build Context: ليه الـ build بياخد دقيقة وفيه الـ .env بتاعك
- 92Multi-stage Builds و Non-root: image صغيرة ومن غير root
- 93Docker Compose والـ Networks: الـ services بتلاقي بعض إزاي
- 94Docker Volumes: الـ data بتتحفَظ فين
- 95Healthcheck و Restart و Resource Limits: running مش معناها شغّال
- 96BuildKit والـ Build Secrets: الـ token ما يدخلش الـ image
- 97Reverse Proxy و TLS: اللي واقف قدام الـ app
- 98Multi-arch Images والـ Native Modules: اشتغلت عندي
- 99CI/CD و Rollback و Canary: الـ deploy يبقى ممل
- 100Kubernetes من الأول: Pods و Deployments و Services و Probes
- 101Modular Monolith و DDD: حدود واضحة من غير network
- 102Transactional Outbox و Inbox: الـ event ما يضيعش وما يتنفذش مرتين
- 103Sagas: عملية واحدة على تلات services من غير transaction واحدة
- 104CQRS و Event Sourcing: الـ events هي الحقيقة
- 105الـ Queues والـ Brokers: BullMQ و RabbitMQ و Kafka و SQS
- 106Realtime على أكتر من instance: Redis pub/sub و presence و resume
- 107الـ Object Storage والـ Media: presigned URLs و uploads مباشرة
- 108التكامل مع الـ Email والـ Search: retries و webhooks و indexes
- 109GraphQL و gRPC في الإنتاج: contracts و DataLoader و limits و deadlines
- 110Kafka على أكتر من zone و region: الـ replication والـ ISR والـ acks والـ MirrorMaker والـ failover
- 111TypeScript و runtime boundaries: الـ types بتختفي، والـ schemas لأ
- 112ORM ولا SQL: query builders و repositories و migrations و transactions
- 113الـ Serverless من جُوّه: cold starts و freeze و timeouts و connections
- 114الـ Testing Pyramid: unit و integration و e2e على Postgres حقيقية
- 115Contract Testing و Property-Based Testing بـ fast-check
- 116الـ Payments: idempotency و webhooks و refunds و reconciliation
- 117الـ Timezones والـ Internationalization: UTC و DST والـ locales والـ plurals والفلوس
- 118الـ Privacy والـ Data Retention: consent و export و erasure و crypto shredding
- 119الـ ADRs والـ Feature Flags: القرارات المكتوبة والـ rollout من غير deploy
- 120Multi-region active-active: حل الـ conflicts بـ HLC و CRDTs
- 121Readiness و Liveness و Startup Probes: الـ pod جاهز ولا عايش؟
- 122Incident Runbooks: من الـ alert للـ postmortem